Write a C++ program to Insert an element in an array after a specific position.
Program Code:
#include<iostream>
using namespace std;
int main()
{
int i, n, no,pos;
int array[100];
cout<<"Enter elements into the Array : ";
cin>>n;
for(i=0;i<n;i++)
{
cin>>array[i];
}
cout<<endl;
cout<<"Entered element into the Array are : ";
for(i=0;i<n;i++)
{
cout<<array[i];
cout<<" ";
}
cout<<endl;
cout<<"Enter position to insert new element into the Array: ";
cin>>pos;
cout<<endl;
if(pos>10)
{
cout<<"This is out of range";
}
else
{
cout<<"Enter new element to be inserted: ";
cin>>no;
cout<<endl;
for(i=n;i>=pos;i--)
{
array[i+1]=array[i];
}
array[pos]=no;
cout<<"After inserting new elements into the Array are : ";
cout<<"After inserting new elements into the Array are : ";
for(i=0;i<n+1;i++)
{
cout<<array[i];
}
}
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Enter elements into the Array : 1 2 3 4 5 6 7 8 9 10
Entered element into the Array are : 1 2 3 4 5 6 7 8 9 10
Enter position to insert new element into the Array: 9
Enter new element to be inserted: 30
After inserting new elements into the Array are : 1 2 3 4 5 6 7 8 9 30 10
Thanks
Mukesh Rajput
Post A Comment:
0 comments: