Inserting element into an Array

Inserting elements into an array
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int n;                                          //intitialising the size of the array
cout<<“Enter the size of the array: “;
cin>>n;                                   //taking the size from the user
int arr[n],i,loc,item;        //initialising array, iteration variable, location, item
cout<<“Enter the elements of the array: “;
for(i=1;i<=n;i++)
{
cin>>arr[i];                        //taking the elements of the array from user
}
cout<<“Enter the location to be inserted: “;
cin>>loc;                          //taking the location from the user
cout<<“Enter the item to be inserted: “;
cin>>item;                      //taking the item from the user
for(i=n;i>=loc;i- – )
{
arr[i+1]=arr[i];            //shifting operation
}
arr[loc]=item;            //inserting the item in that location
for(i=1;i<=n+1;i++)
{
cout<<arr[i]<<“\t”;    //displaying the elements
}
getch();
}
* Algorithm of the above program:
Insert (ARR,LOC,ITEM,N)
1. Repeat for  I=N to LOC
2.    Set ARR[I+1] = ARR[I]    //Shift the elements downwards
[End of loop]
3. Set ARR[LOC] = ITEM.        //insert the item in that location
4. N = N+1                                   //Reset size of the array
5. Exit
* Complexity: O(n)
Note:
1. For inserting an element in an array, we have to shift the last element to the next location till the location of the new item to be inserted reach. Then we can insert the new element to the location.

 

Author: Udipto Goswami

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s