C Program to delete the duplicate elements in an array

CServer Side ProgrammingProgramming

Try to delete the same numbers present in an array. The resultant array consists of unique elements.

The logic to delete the duplicate elements in an array is as follows −

for(i=0;i<number;i++){
   for(j = i+1; j < number; j++){
      if(a[i] == a[j]){
         for(k = j; k <number; k++){
            a[k] = a[k+1];
         }
         j--;
         number--;
      }
   }
}

The logic to display the numbers after deleting the duplicates is as follows −

for(i=0;i<number;i++){
   printf("%d ",a[i]);
}

Program

Following is the C program to delete the duplicate elements in an array.

 Live Demo

#include<stdio.h>
#include<stdlib.h>
int main(){
   int a[50],i,j,k, count = 0, dup[50], number;
   printf("Enter size of the array\n");
   scanf("%d",&number);
   printf("Enter Elements of the array:\n");
   for(i=0;i<number;i++){
      scanf("%d",&a[i]);
      dup[i] = -1;
   }
   printf("Entered element are: \n");
   for(i=0;i<number;i++){
      printf("%d ",a[i]);
   }
   for(i=0;i<number;i++){
      for(j = i+1; j < number; j++){
         if(a[i] == a[j]){
            for(k = j; k <number; k++){
               a[k] = a[k+1];
            }
            j--;
            number--;
         }
      }
   }
   printf("\nAfter deleting the duplicate element the Array is:\n");
   for(i=0;i<number;i++){
      printf("%d ",a[i]);
   }
}

Output

When the above program is executed, it produces the following result −

Enter size of the array
10
Enter Elements of the array:
1 1 2 4 3 5 6 5 7 1
Entered element are:
1 1 2 4 3 5 6 5 7 1
After deleting the duplicate element, the Array is:
1 2 4 3 5 6 7
raja
Published on 12-Mar-2021 11:16:37
Advertisements