Example: If elements of the array are: 1, 2, 3, 5, 1, 5, 20, 2, 12, 10
All unique elements in the array are: 3, 20, 12, 10
Required knowledge:
Basic C programming, For loop, ArrayProgram:
/**
* C program to print all unique elements in array
*/
#include <stdio.h>
int main()
{
int arr[100], size, isUnique;
int i, j, k; //Used for loops
/*
* Reads size of the array
*/
printf("Enter size of array: ");
scanf("%d", &size);
/*
* Reads elements in array
*/
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/*
* Removes all duplicate elements from array
*/
for(i=0; i<size; i++)
{
/* Assumes that the current array element is unique */
isUnique = 1;
for(j=i+1; j<size; j++)
{
/*
* If any duplicate element is found
*/
if(arr[i]==arr[j])
{
/* Remove the duplicate element */
for(k=j; k<size-1; k++)
{
arr[k] = arr[k+1];
}
size--;
j--;
isUnique = 0;
}
}
/*
* If array element is not unique
* then also remove the current element
*/
if(isUnique != 1)
{
for(j=i; j<size-1; j++)
{
arr[j] = arr[j+1];
}
size--;
i--;
}
}
/*
* Prints all unique elements in array
*/
printf("\nAll unique elements in the array are: ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}
Output
Enter size of array: 10
Enter elements in array: 1 2 3 5 1 5 20 2 12 10
All unique elements in the array are: 3 20 12 10
Enter elements in array: 1 2 3 5 1 5 20 2 12 10
All unique elements in the array are: 3 20 12 10
Happy coding ;)
You may also like
- Array programming exercises index.
- C program to print all natural numbers from 1 to n.
- C program to print all alphabets from a to z.
- C program to print sum of all odd numbers from 1 to n.
- C program to find LCM of any two numbers.
- C program to find sum of all elements of an array.
- C program to find maximum and minimum elements in array.
- C program to insert an element in array at specified position.
- C program to delete an element at specified position from array.
- C program to find reverse of an array.
- C program to search an element in the array.
- C program to merge two array in a single array.
- C program to count frequency of each element of array.
- C program to sort elements of array in ascending order.
- C program to sort elements of an array in descending order.