Monday, September 12, 2011

Delete an element from the Array

// Delete an element from the Array
#include<stdio.h>
#include<conio.h>
main()
{
    int a[15],n,i,j,flag=0,item,num;
    clrscr();
    printf("\n How many elements : ");
    scanf("%d",&n);
    num=n;  //It wll be used to find the no. of duplicates
    for(i=0;i<n;i++)
        {
        printf("\n enter the element no. %d: ",i+1);
        scanf("%d",&a[i]);
        }
    printf("\n The elements are: \n");
    for(i=0;i<n;i++)
        printf(" %d ",a[i]);
    printf("\n enter the element to be deleted : ");
    scanf("%d",&item);



    for(i=0;i<n;i++)        // Main logic
       {
          if(a[i]==item)     // i.e. item is found in the array
        {
            flag=1;
            for(j=i;j<n;j++)
            a[j]=a[j+1]; //using shifting, item is deleted
            n--;
        }    // Looping to check whether more 'item' ;left or not
       }  //end of main logic

       if(flag==0)
        printf("\n element not found  ");
       else
       {
      printf("\n Array has %d duplicates",num-n);
      printf("\n Array after deletion \n");
      for(i=0;i<n;i++)
        printf(" %d ",a[i]);
    }
    getch();
 }

No comments:

Post a Comment

Popular 5 Posts Last 7 days