C++ Program to Insert an Element in an Array

In this tutorial, I am going to teach you “C++ Program to Insert an Element in an Array”. Full source code of the application is given below.

C++ Program to Insert an Element in an Array

C++ Program to Insert an Element in an Array

Source Code

#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<<"nnArray after inserting element:n";
for(i=0;i<n+1;i++)
cout<<a[i]<<" ";
 
return 0;
}

Final Words

I hope this article helps you to learn “C++ Program to Insert an Element in an Array“. If you face any issues please let me know via the comment section. Share this article with other C/C++ developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment