Print all unique elements in an array
C program to print all unique elements in an array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_unique(int a[MAX], int freq[MAX], int n)
{
int i, j, count;
printf("\nunique elements in the array are\t:");
for(i=0;i<n;i++)
{
freq[i] = -1;
}
for(i=0;i<n;i++)
{
count = 1;
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
count++;
freq[j] = 0;;
}
}
if(freq[i] != 0)
{
freq[i] = count;
}
}
for(i=0;i<n;i++)
{
if(freq[i] == 1)
{
printf("%d,\t",a[i]);
}
}
}
void main()
{
int arr[MAX], freq[MAX];
int i, n;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
print_unique(arr, freq, n);
getch();
}
Output
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :12
Element 2 :23
Element 3 :21
Element 4 :32
Element 5 :23
Element 6 :21
Element 7 :25
Element 8 :56
unique elements in the array are :12, 32, 25, 56,