Thursday, 1 June 2017

Remove Duplicate Element from Array in C ~ GNIITHELP

Program to Remove duplicate Element in an Array

Below is a simple and easy to understand program to find and remove any duplicate element present in specified array.
#include<stdio.h>
#include<conio.h>
void main()
{
   int a[20], i, j, k, n;
   clrscr();
   
   printf("\nEnter array size : ");
   scanf("%d",&n);

   printf("\nEnter %d array element : ", n);
   for(i = 0; i < n; i++) 
   {
      scanf("%d",&a[i]);
   }
   
   printf("\nOriginal array is : ");
   for(i=0;i< n;i++)
   {
      printf(" %d",a[i]);
   }

   printf("\nNew array is  : ");
   for(i=0; i < n; i++) 
   {
      for(j=i+1; j < n; )
      {
         if(a[j] == a[i])
         {
            for(k=j; k < n;k++) 
            {
               a[k] = a[k+1];
            }
            n--;
         }
         else {
            j++;
         }
      }
   }

   for(i=0; i < n; i++)
   {
      printf("%d ", a[i]);
   }
getch();
}
Output
Enter array size : 5
Enter 5 array element :  11 13 11 12 13
Original array is :  11 13 11 12 13
New array is :  11 13 12

No comments:

Post a Comment