Here in this program, we will code to insert Insert an element in an Array that is one-dimensional with C++ and Python:
Write a program in C++ & Python to Insert an Element in an Array
C++
#include<iostream.h> #include< conio.h> #include<stdio.h> #include<math.h> void main() { clrscr(); int arr[10],n,pos=0,in; cout<<"How many elements you want to enter in the array: "; cin>>n; cout<<"Enter the array elements in Ascending order:"<<endl; for(int i=0;i<n;i++) {cin>>arr[i]; } cout<<"Enter the Element you want to insert: "; cin>>in; for(i=0; i<n;i++) if(arr[i]<=in && in<arr[i+1]) {pos= i+1; break; } for(j=n+1; j>pos;j--) arr[j]=arr[j-1]; arr[pos]=in; cout<<"The element has been inserted:"; for(i=0;i<n+1;i++) cout<<arr[i]<<" " ; getch(); }
Output:
How many elements you want to enter in the array: 5 Enter the array elements in Ascending order: 1 23 34 45 57 Enter the Element you want to insert: 36 1 23 34 36 45 57
Python
arr=[] pos=0 n=int(input("How many elements you want to enter in the array: ")) print("Enter the array elements in Ascending order:") for i in range(n): arr.append(int(input())) inp= int(input("Enter the Element you want to insert: ")) for i in range(len(arr)): if ((arr[i]<=inp) and (inp<arr[i+1])): pos = i+1 break if pos <len(arr): arr.insert(pos,inp) else: arr.append(inp) for i in range(len(arr)): print(arr[i],end=' ')
Output:
How many elements you want to enter in the array: 5 Enter the array elements in Ascending order: 1 23 34 45 57 Enter the Element you want to insert: 36 1 23 34 36 45 57
People are also reading:
- C++ & Python program to print the ASCII value of a character
- WAP to print the truth table for XY+Z
- WAP in C++ & Python to convert a given number of days into years, weeks and days
- WAP to print the 1 to 10 Multiples of a Number
- Python Program to Print the Fibonacci sequence
- WAP in C++ & Python to raise any number x to a Positive Power n
- WAP to print three numbers in descending order
- WAP in C++ & Python to find whether a number is a palindrome or not
- Python Program to Check Armstrong Number
Leave a Comment on this Post