C++ Program to Insert an Element in an Array

Here is the C++ program to insert an element in an array. The array must be in ascending order.

For example the array is 1 4 6 7.

We have to insert 5.

Then the resultant array will be 1 4 5 6 7.

The program is given below.

C++ Program to Insert an Element in an Array

#include<iostream>

using namespace std;

int main()
{
	int a[20],n,x,i,pos=0;
	cout<<"Enter size of array:";
	cin>>n;
	cout<<"Enter the array in ascending order:\n";
	
	for(i=0;i<n;++i)
		cin>>a[i];
	
	cout<<"\nEnter element to insert:";
	cin>>x;
	
	for(i=0;i<n;++i)
		if(a[i]<=x&&x<a[i+1])
		{
			pos=i+1;
			break;
		}
		
	for(i=n+1;i>pos;--i)
		a[i]=a[i-1];
	
	a[pos]=x;
	
	cout<<"\n\nArray after inserting element:\n";
	
	for(i=0;i<n+1;i++)
		cout<<a[i]<<" ";

	return 0;
}

 

Output

Enter size of array:5
Enter the array in ascending order:
1 3 4 6 9

Enter element to insert:2
Array after inserting element:
1 2 3 4 6 9

8 thoughts on “C++ Program to Insert an Element in an Array”

  1. try it guys……..

    #include
    using namespace std;
    int main()
    {
    int a[100];
    int len = sizeof(a)/sizeof(a[0]);
    int i,n,l,item;
    cout<>n;
    if(n>=len)cout<<"Sorry no space for insertion ";
    else{
    cout<<n<<" Elements : ";
    for(i=0;i>a[i];
    cout<>l;
    cout<>item;
    for(i=n;i>=l;i–){a[i]=a[i-1];}
    a[l-1]=item;
    n=n+1;

    cout<<"result : "<<endl;
    for(i=0;i<n;i++)cout<<a[i]<<" ";

    }
    }

Leave a Comment

Your email address will not be published. Required fields are marked *