Insertion of an Element in An Array

Insert an element in any given array in C++. The concept is implemented by moving all the elements

#include<iostream>
#include<iomanip>
using namespace std;

void input(int x[], int n){
  for(int i=0;i<n;i++)
    {
      cout<<"Enter "<<i<<" element :";
      cin>>x[i];
    }
  return;
}

void output(int x[], int n){
  for(int i=0;i<n;i++)
    cout<<setw(6)<<x[i];
  return;
}

void insert_element(int x[], int n, int &m, int value, int pos)
 {
 	if(m>=n){
 		cout<<"Array already full. Can't insert element";
   }
  else
  {
    for(int i=m-1;i>=pos-1;i--)
      x[i+1]= x[i];
    x[pos-1]=value;
    m = m+1;
  }
  return;
 }
 
 int main(){
 	int x[10],m, pos, value;
 	//input phase
 	cout<<"Enter size of filled position :";
 	cin>>m;
 	input(x,m);
 	
 	cout<<"\n Enter value that you want to insert  :";
 	cin>>value;
 	cout<<"\n Enter position :";
 	cin>>pos;
 	
 	//processing phase
 	insert_element(x,10,m,value,pos);
 	
 	//output
 	cout<<"\n\nArray after insertion \n";
 	output(x,m);
 	
 }

The output of the above program is as follows

Enter size of filled position :5
Enter 0 element :12
Enter 1 element :34
Enter 2 element :56
Enter 3 element :67
Enter 4 element :89

 Enter value that you want to insert  :3

 Enter position :100


Array after insertion
    12    34    56    67    89     0
--------------------------------

If you have any issue/query regardding this code. Please send us your queries through comments.

one place lower up to the selected position and then place your desired value at the given position.

 

Leave a Reply

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