C program to print all unique elements in an array

Write a C program to read elements in an array and print all unique element present in array. C program to find unique/distinct elements in an array. Logic to print all unique elements in an array in C program.

Array unique elements

Example

Input

Input array elements: 1, 2, 3, 5, 1, 5, 20, 2, 12, 10

Output

All unique elements in the array are: 3, 20, 12, 10

Required knowledge

Basic C programming, For loop, Array

Logic to find all unique elements in array

Below is the step by step descriptive logic to find all unique elements in given array

  1. Input size and elements in array. Store it in some variable say size and arr.
  2. Find frequency of each element and store it in some variable say freq.
  3. Print the array elements with frequency 1 which is the required unique elements.

Program to print all unique elements in array

/**
 * C program to print all unique elements in array
 */

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
    int arr[MAX_SIZE], freq[MAX_SIZE];
    int size, i, j, count;
 
    /* Input size of array and elements in array */
    printf("Enter size of array: ");
    scanf("%d", &size);
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
        freq[i] = -1;
    }
 
    /* Find frequency of each element */
    for(i=0; i<size; i++)
    {
        count = 1;
        for(j=i+1; j<size; j++)
        {
            if(arr[i]==arr[j])
            {
                count++;
                freq[j] = 0;
            }
        }
 
        if(freq[i]!=0)
        {
            freq[i] = count;
        }
    }
 
    /* Print all unique elements of array */
    printf("\nUnique elements in the array are: ");
    for(i=0; i<size; i++)
    {
        if(freq[i] == 1)
        {
            printf("%d ", arr[i]);
        }
    }

    return 0;
}

Output

Enter size of array: 10
Enter elements in array: 1 2 3 5 1 5 20 2 12 10

Unique elements in the array are: 3 20 12 10

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>