C program for removing duplicate element in an array

remove duplicate elements in C

Remove duplicate elements in an array

Let’s learn about removing duplicate elements in an array using C programming language. Removing duplicate elements in an array means to remove elements which occurs more than once. After removing all duplicate elements each and every element present in that array will be unique. See the below example for better understanding.

Example:

Input:

  • Size of array= 6
  • Array elements = { 78 , 23 , 37 , 98 , 37 , 78 }

Output:

  • Array without duplicates= { 78 , 23 , 37 , 98 }

Check out below algorithm and Code to implement removing duplicate elements in an array using C

remove duplicate elements in C

Algorithm:

  • Start
  • Input the number of elements of the array.
  • Input the array elements.
  • Iterate through every element in the array 
  • Find if any element is repeated or not
  • At every iteration print the number with a space if count is 1. If count is not equal to 1 then do not print anything as it is not a unique number
  • Print

C Code:

#include <iostream>

using namespace std;

int main()
{
int arr[50],n;
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("After removing the duplicates: ");
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[i]==arr[j])
{
while(j<n)
{
arr[j]=arr[j+1];
j++;
}
--n;
}
else{
continue;
}
}
}

for(int i=0;i<n;i++)
{
printf("%d ",arr[i]);
}

return 0;
}

Test case 1

Enter the size of array: 6
Enter the elements: 12
11
13
11
14
15
After removing the duplicates: 12 11 13 14 15
Enter the size of array: 4
Enter the elements: 1
2
3
1
After removing the duplicates: 1 2 3