Interview Questions   Tutorials   Discussions   Programs   Videos   

C++ - Write a program to insert an element into an array?




294
views
asked marvit August 18, 2014 08:40 PM  

Write a program to insert an element into an array?


           

1 Answers



 
answered By bhjahnavi   0  
/*program that inserts an element into an array*/
#include<iostream.h>
#include<conio.h>

void 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:";

 for(i=0;i<n+1;i++)
 cout<<a[i]<<" ";
 getch();
}
flag   
   add comment

Your answer

Join with account you already have

FF

Preview


Ready to start your tutorial with us? That's great! Send us an email and we will get back to you as soon as possible!

Alert