DATA STRUCTURES

  • Home
  • DATA STRUCTURES USING C++


Admission Enquiry Form

What is deletion in Array.

Deletion in an array here means delete an element from a given location in an array.

deletion from an array by compuhelp




Algorithm of deletion in an Array

Delete(A,N,LOC) [LOC is the location of the element to be deleted]

Step1. START

Step2. Repeat for I = LOC to N – 1, I<-I+1

             A[I] <- A[I+1] [Move element with index I+1 left by 1]

             [End of loop]

Step3.  N <- N-1   [Reset the size of A to N-1]

Step4.  END

 




Program of deletion in an Array.

//Array Data Structures
#include<iostream>
using namespace std;
#define SIZE 10
int arr[SIZE];
int pos=-1;
void addEnd(int value)
{
if(pos<(SIZE-1))
{
pos++;
arr[pos]=value;
}
else
{
cout<<endl<<"Array is full ";
}

}//end of function
void addBeg(int value)
{
if(pos<(SIZE-1))
{
for(int i=pos;i>=0;i--)
{
arr[i+1]=arr[i];
}
arr[0]=value;
pos++;
cout<<endl<<"value added in the beginning";
}
else
{
cout<<endl<<"Array is full";
}
}//end of function addBeg
void display()
{
cout<<endl<<"Elements of array are :"<<endl;

for(int i=0;i<=pos;i++)
{
cout<<arr[i]<<" ";
}//end of for

}//end of function display
void addMid(int index,int value)
{

for(int i=pos;i>=index;i--)
{
arr[i+1]=arr[i];
}
arr[index]=value;
pos++;
cout<<endl<<"Value added at index "<<index;

}//end of function addMid
void delEnd()
{
if(pos>=0)
{
pos--;
cout<<endl<<"Element deleted...";
}
else
{
cout<<endl<<"Array is empty";
}

}//end of function delEnd
void delBeg()
{
if(pos>=0)
{
for(int i=0;i<=pos;i++)
{
arr[i]=arr[i+1];
}
pos--;
cout<<endl<<"Element deleted from ";
}
else
{
cout<<endl<<"Array is Empty";
}

}//end of function delBeg

int main()
{
addEnd(10);
addEnd(20);
addEnd(30);
addEnd(40);
display();
addBeg(100);
display();
addBeg(90);
display();
addMid(2,500);
display();
delEnd();
display();
delBeg();
display();

//display();
}




Program of deletion in an Array.

#include<iostream>
using namespace std;
void delete_array(int array[],int *n,int loc)
{
int i;
if (loc >= *n+1 )
{
cout<<"Deletion not possible.\n";
}
else
{
for ( i = loc - 1 ; i < *n - 1 ; i++ )
{
array[i] = array[i+1];
}
*n=*n-1;
}
}//end of method delete_array
int main()
{
int array[100], loc, i, n;

cout<<"Enter number of elements in array\n";
cin>>n;

cout<<"Enter "<<n<<" elements\n";

for ( i = 0 ; i < n ; i++ )
{
cin>>array[i];
}
cout<<"Enter the location from where you want to delete an element\n";
cin>>loc;
loc=loc;
delete_array(array,&n,loc);
cout<<"Resultant array is\n";

for( i = 0 ; i < n ; i++ )
{
cout<<array[i]<<endl;
}
return 0;
}//end of main function