This c++ program inserts an element into an array in a given position. The variable n reads the limit of the array. Then the numbers are read one by one into the array a[]. Next the element to be inserted and the position of insertion is read to the variables elem and pos. Then the program uses a for loop to make space of the new element in the array and the new element is inserted into the given position and the new array is displayed to the output screen.
Program
#include<iostream.h> #include<conio.h> void main() { int a[50],n,i,*p,pos,elem; cout<<"Enter the value for n: "; cin>>n; cout<<"\nEnter the elements\n"; for(i=0;i<n;i++) { cin>>a[i]; } cout<<"\nEnter the element and position to insert: "; cin>>elem>>pos; p=&a[n]; for(i=n;i>pos;i--) { *(p)=*(p-1); p--; } a[pos]=elem; p=a; cout<<"\nArray after insertion\n\n"; for(i=0;i<=n;i++) { cout<<*(p+i)<<"\t"; } getch(); }
C++: Insert an element into an array |
No comments:
Post a Comment