Insert an Element in an Array at specific position
Here you will get an example code of C++ program to insert an element in an array at specific position. This is an example of single dimensional array.
Example of C++ Program to Insert an Element in an Array at specific position
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include<iostream> using namespace std; int main() { int i, ar[50], k,n,item; cout<<"\nEnter the size of the array : "; cin>>n; cout<<"\nEnter elements of array : "; for(i=0;i<=(n-1);i++) { cin>>ar[i]; } cout<<"\nEnter the location of the element to insert : "; cin>>k; cout<<"\nEnter element value to insert : "; cin>>item; i=n-1; while(i>=k-1) { ar[i+1]=ar[i]; i--; } ar[k-1]=item; cout<<"\n\n\nArray elements are : "; for(i=0;i<=n;i++) { cout<<" "<<ar[i]; } return 0; } |
Output:
Enter the size of the array : 7
Enter elements of array : 3
5
2
8
7
1
9
Enter the location of the element to insert : 4
Enter element value to insert : 4
Array elements are : 3 5 2 4 8 7 1 9
Check out our other C++ programming Examples