Facebook

Deletion of element from array

Deleting  an  element means to remove element from the array.It is quite easy to delete the element from the end of array.On the controversial side,what is needed to delete the element from our  desired location  like somewhere in the middle of array .Deleting an element requires that all the subsequent elements must be moved one location up to keep the order of array.

The following program is to delete element from the end of array.

Program

#include <stdio.h>

int main()
{
   int arr[10] = {10,20,30,40,50};
   int pos;
   int i;
   printf("Enter the location where you wish to delete element\n");
   scanf("%d", &pos);
   if ( pos > 4 )
      printf("Deletion not possible.\n");
   else
   {
     for ( i = pos  ; i < 4 ; i++ )
     {
     a[i] = a[i + 1];
     }
     printf("Resultant array is\n");
     for( i = 0 ; i < 4 ; i++ )
     {
      printf("%d\t", arr[i]);
      }
   }  

return 0;
}
Run

Illustration of Program

  • Array arr  of  integer type and size 10 is initialized with values 10,20,30,40,50.(Fig 1)
  • pos is the location from where user wants to delete the element.Say user enters 2.
  • The location of elements varies from 0 to 4 as 5 values are initialized.If user enters any location greater than 5,then deletion is not possible since element is not present at that location.
  • Working of for loops is explained in Fig 2.
Fig 1 : Elements of array before deletion.
Fig 1 : Elements of array before deletion.
Fig 2 : Working of for loops
Fig 2 : Working of for loops
Fig 3 :Elements after deletion of 30 at 2 position.
Fig 3 :Elements after deletion of 30 at 2 position.

 

 

Rate this post

Comments

So empty here ... leave a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sidebar