C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Find unique elements in an array

C Program: Find unique elements in an array

C

#include <stdio.h>

 

int main() {

    int arr[100], freq[100];

    int n, i, j, count;

 

    // Input array size

    printf("Enter number of elements in the array: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

        freq[i] = -1;  // Initialize frequency array

    }

 

    // Count frequency of each element

    for (i = 0; i < n; i++) {

        count = 1;

        for (j = i + 1; j < n; j++) {

            if (arr[i] == arr[j]) {

                count++;

                freq[j] = 0; // Mark element as counted

            }

        }

        if (freq[i] != 0)

            freq[i] = count;

    }

 

    // Display unique elements

    printf("\nUnique elements in the array:\n");

    for (i = 0; i < n; i++) {

        if (freq[i] == 1) {

            printf("%d ", arr[i]);

        }

    }

 

    printf("\n");

    return 0;

}

Output

 
INPUT :
Enter number of elements in the array: 8
Enter 8 elements:
2 3 2 5 3 4 5 7

OUTPUT :
Unique elements in the array:
4 7

Explanation

  1. The program reads array elements and initializes a frequency tracker.
  2. Using nested loops, it counts occurrences of each element.
  3. Elements that appear more than once are marked.
  4. Finally, only elements with frequency 1 are printed as unique elements.