Deleting element from an array

Deleting element in an array

#include<iostream>

#include<conio.h>

using namespace std;

main()

{

int n;                                      //initialising the size of an array

cout<<“Enter the size of the array: “;

cin>>n;                                 //Taking the size from the user

int arr[n],i=1,loc;

cout<<“Enter the elements of the array: “;

while(i<=n)                         //While loop

{

cin>>arr[i];                               //Taking the elements form the user

i++;                                              //Increment the iteration variable

}

cout<<“Enter the location to be deleted: “;

cin>>loc;                            //Taking the value of location from the user

i=loc;                                   //Initialise the iteration variable

while(i<=n)                      //while loop

{

arr[i]=arr[i+1];                        //shifting the elements upward

i++;

}

i=1;

while(i<n)

{

cout<<arr[i]<<“\t”;               //Displaying the elements

i++;

}

getch();

}

* Algorithm of the above program:

Delete (ARR, LOC, N)

  1. Set I=LOC                                            //Initialise counter/iteration variable
  2. Repeat steps 3 and 4 while I<=N
  3. Set ARR[I] = ARR[I+1]                    //shifting the elements upwards
  4. Set I = I+1;                                          //Increment the counter

[End of loop]

  1. Set N=N-1;                                      //Reset the size of the array
  2. Exit

* Complexity = O(n)

Note:

  1. For deleting element from an array, the elements are needed to be shifted upwards starting from the location that we want to delete. Then the size of the array should be reduced.
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