C Program to Print Unique Elements of An Unsorted Array

• Write a C program to print unique elements of an array.

Given an unsorted array of length N, we have to print the unique elements of array. If there are three occurrences of 5 then we have to print 5 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.

For Example

Input Array: 8 3 6 1 7 3 7 8
Unique elements : 8 3 6 1 7

Algorithm to find unique elements of unsorted array

• First of all, take N numbers as input from user and store it in an array(lets call it inputArray).
• We will start traversing inputArray 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.

Time Complexity : O(n2)

C program to find unique elements of an unsorted array

/*
* C program to print all unique elements of an unsorted array
*/
#include<stdio.h>
#include<conio.h>

int main() {
int array[100], size, i, j;

printf("Enter number of elements in array\n");
scanf("%d", &size);
printf("Enter %d numbers\n", size);

for(i = 0; i < size; i++){
scanf("%d", &array[i]);
}

printf("Unique Elements\n");
for(i = 0; i < size; i++) {
for (j=0; j<i; j++){
if (array[i] == array[j])
break;
}

if (i == j){
/* No duplicate element found between index 0 to i */
printf("%d ", array[i]);
}
}

getch();
return 0;
}

Program Output

Enter number of elements in array
10
Enter 10 numbers
1 2 8 5 2 3 8 4 1 6
Unique Elements
1 2 8 5 3 4 6