Deletion inside data structures is very common, especially inside arrays as they have static(fixed) memory allocation. To delete an element from the array simply move each element one step above. For example, if the array was initially as follows :
Element 0 : 23Element 1 : 98
Element 2 : 87
Element 3 : 12
and suppose we want to delete an element at the 1st position(i.e.98), then we simply shift each element one position above. So, the new array after deleting value 98 from the 1st position would be as follows :
Element 0 : 23
Element 1 : 87
Element 2 : 12
Hence we have successfully deleted an element from the array. The process is contrary to the method that we have used to perform insertion operation in the array(see the previous post). Read the given code below, for a better understanding :
// Program to delete element in an array (for GCC compiler package and similar compilers)
#include <iostream>
// function to delete an element from the array
int deletion_array(int array[],int s,int pos)
{
for (int i=pos; i<=s; i++)
{
array[i] = array[i+1]; //shifts each element one position above
}
s--; // decrements the size, as one element is deleted
return s; // returns the new size of the new array
}
int main()
{
int size,value,position;
int arr[21];
// prompts the used to enter the maximum no. of elements in the array
std::cout<<" Enter the no of elements you want in the array (max 20) : ";
std::cin>>size;
// to insert the elements in the array
for (int i=0; i<size; i++)
{
std::cout<<" \n Element "<<i<<" : ";
std::cin>>arr[i];
}
std::cout<<"\n Enter the position where you want to delete the value : ";
std::cin>>position;
size = deletion_array(arr,size,position);
// calls the function to delete the specified element
std::cout<<" \n Deletion successfull !!! , the new array is as follows ";
for (int i=0; i<size; i++)
{
std::cout<<"\n Element "<<i<<" : "<<arr[i];
}
return 0;
} // end of main
Note : If the console window shuts down immedeaitly, then add std::cin.get(); before return 0; to fix the problem. :)
------ OUTPUT ------
------ Related Posts ------
Insertion in array : http://programsplusplus.blogspot.in/2012/02/insertion-in-integer-array.html
it is a very good pgm which helped me 2 understand deletion
ReplyDeletethank u:)
You are welcome adarsh...:)
Delete