Inserting element into an Array

Inserting elements into an array
using namespace std;
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: “;
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
cout<<arr[i]<<“\t”;    //displaying the elements
* Algorithm of the above program:
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)
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


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s