Delete Duplicate Elements in an Array in C



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
"
);    scanf("%d",&number);    printf("Enter Elements of the array:
"
);    for(i=0;i<number;i++){       scanf("%d",&a[i]);       dup[i] = -1;    }    printf("Entered element are:
"
);    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("
After deleting the duplicate element the Array is:
"
);    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
Updated on: 2023-09-12T03:23:56+05:30

50K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements