C program to print the unique elements in an unsorted array
Write a C program to print the unique elements in an unsorted array.
In this c program, we have to print the unique elements for the given Unsorted Array of length N. For example : If there are three occurrences of 7 then we have to print 7 only once.
We can find the unique element in an array by traversing the array from index 0 to N-1 and for each element again traversing the array to find any duplicated element.
C Programming Code
#include<stdio.h>
int main()
{
int n;
printf(“Enter array size: “);
scanf(“%d”, &n);
int a[n];
printf(“Enter %d numbers: “, n);
for(int i=0; i<n; i++)
scanf(“%d”, &a[i]);
int temp = a[0];
for(int i=1; i<n; i++)
{
temp = temp ^ a[i];
}
printf(“Unique element in the array is: %d”, temp);
return 0;
}
Logic behind the Program
Take input from the users and store it in an array(lets call it inputArray).
We will start traversing input Array from index 0 to N -1 and for any element at index i(inputArray[i]), we will search for duplicate element from index 0 to i.
If we find a duplicate element then we skip current element otherwise print it on screen.