C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Frequency of Each Element in an Array

C Program: Count Frequency of Each Element 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 frequency of each element

    printf("\nFrequency of each element:\n");

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

        if (freq[i] != 0) {

            printf("%d occurs %d time(s)\n", arr[i], freq[i]);

        }

    }

 

    return 0;

}

Output

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


OUTPUT :
Frequency of each element:
2 occurs 3 time(s)
3 occurs 2 time(s)
5 occurs 2 time(s)
4 occurs 1 time(s)

Explanation

  1. The program reads the size and elements of the array.
  2. A parallel array freq[] keeps track of the frequency of each element.
  3. Nested loops count how many times each element appears.
  4. Duplicate elements are marked to avoid recounting.
  5. Finally, the program prints each unique element with its frequency.