Tuesday, 14 February 2017

C Program to Delete an Element at any position in the Array

Arrays is that type of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Deletion in array refers to removing an existing element from the array and re-organizing all elements of an array.

ALGORITHM
Set item:= the element to be deleted
For i in range 1 to i<=n:   #n be the total number of elements in array
    if array[i]==item:
        For j in range i to j<=n:
             Set: array[j]=array[j+1]
             Set: j=j+1
        End For Loop
        Set n:=n-1
        Break
    EndIf
End For
EXIT

PROGRAM:

#include <stdio.h>

#define MAX 100

int array[MAX],n;

int delete();

void print();

int main()

{

  int i,deleted;

  printf("\nEnter the total number of elements: ");

  scanf("%d",&n);

  printf("\nEnter the elements of array:\n ");

  for(i=0;i<n;i++)

  {

      scanf("%d",&array[i]);

  }

  print();

  deleted=delete();

  print();

  printf("\nDeleted item is: %d",deleted);

         printf("\n");

  return 0;

}

void print()

{

 int i;

 printf("\n\nThe updated array is: \n");

 for(i=0;i<n;i++)

 {

           printf("%d ",array[i]);

 }

}

int delete()

{

 int item,i,j;

 printf("\nEnter the element you want to delete from the array: ");

 scanf("%d",&item);

 for(i=0;i<n;i++)

 {

         if(array[i]==item)

         {

             for(j=i;j<n;j++)

             {

                   array[j]=array[j+1];

             }

             n=n-1;

             break;

         }

 }

 return item;

}


OUTPUT:

 


EmoticonEmoticon