C Program to Find the Frequency of Elements in an Array

C Program to Find the Frequency of Elements in an Array

When working with arrays in C, one of the useful operations is finding how many times each element appears. This is called the frequency of elements in the array. For example, in an array like {2, 3, 2, 4, 3, 2}, the number 2 appears three times, the number 3 appears two times, and the number 4 appears once.

Counting frequency is an important exercise because it strengthens your ability to handle arrays, loops, and conditions in C. It also introduces the idea of tracking occurrences, which is commonly used in real-world programs such as word counting, data analysis, and duplicate detection. In this tutorial, we will write a C program to find the frequency of each element in an array.

Understanding the Problem

The task is simple: for each element in the array, we need to count how many times it appears. One way to do this is by traversing the array, marking elements that have already been counted, and then printing their frequency. For example, in the array {1, 2, 3, 2, 1}, the output shows that 1 appears 2 times, 2 appears 2 times, and 3 appears 1 time. This requires us to loop through the array carefully, making sure not to count the same element more than once.

C Program to Find Frequency of Elements

The following program finds the frequency of each element without using extra data structures. It uses an auxiliary array to mark elements that have already been counted.

#include <stdio.h>

int main() {

    int n, i, j, count;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int arr[n];
    int freq[n];

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

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

        scanf("%d", &arr[i]);
        freq[i] = -1; // initialize frequency array

    }

    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 as visited

            }

        }

        if(freq[i] != 0) {
            freq[i] = count;
        }

    }

    printf("\nFrequency of elements:\n");

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

        if(freq[i] != 0) {
            printf("%d occurs %d times\n", arr[i], freq[i]);
        }

    }

    return 0;

}

In this program, the array arr holds the input numbers, and another array freq is used to track whether an element has already been counted. Each position in freq is initialized to -1.

The outer loop picks each element one by one. For every element, the inner loop checks all following elements to see if they match. If a match is found, the count is increased and the frequency for that position is marked as 0 to indicate that it has already been considered. After finishing the inner loop, if the current element is not marked as visited, its frequency is stored. Finally, the program prints each unique element with the number of times it occurs.

Alternative Approach Using Hashing (Efficient Way)

If the range of elements is small, we can use an auxiliary array (acting like a hash map) to count frequencies more efficiently.

#include <stdio.h>

int main() {

    int n, i;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int arr[n];

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

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

    int freq[1000] = {0}; // assuming elements are less than 1000

    for(i = 0; i < n; i++) {
        freq[arr[i]]++;
    }

    printf("\nFrequency of elements:\n");

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

        if(freq[i] > 0) {
            printf("%d occurs %d times\n", i, freq[i]);
        }

    }

    return 0;

}

This program works by directly increasing the frequency count at the index equal to the element’s value. It is faster because it avoids nested loops, but it requires knowing the maximum possible value in advance.

FAQs

Q1: Can this program handle negative numbers?
Yes, the first method using nested loops works fine with negative numbers. The hashing method would need adjustment, such as offsetting indexes.

Q2: Which method is better?
For small arrays, the nested loop method is simple and works well. For large arrays with limited range of numbers, the hashing method is much faster.

Q3: What happens if the array is empty?
If the array has zero elements, the program will not enter the loops and nothing will be printed.

Q4: Can I modify this program to find the most frequent element only?
Yes, by keeping track of the maximum frequency while counting, you can identify the most repeated element.

Conclusion

Finding the frequency of elements in an array is a basic but very useful problem in C programming. It introduces important ideas like array traversal, nested loops, auxiliary arrays, and optimization techniques. The nested loop approach is simple and universal, while the hashing approach provides efficiency when conditions allow. Mastering this program builds a solid foundation for solving more advanced problems involving arrays and data analysis.

References & Additional Resources

A curated selection of textbooks and tutorials to understand arrays in C and techniques for counting element frequencies.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988.
  2. GeeksforGeeks: C Program To Count Frequency of Each Element in an Array – Shows how to count the frequency of elements in an array by first sorting, then applying binary search to determine lower and upper bounds for each unique element.
  3. TutorialsPoint: Arrays in C – A straightforward guide to the basics of arrays: declaration, initialization, and manipulation in C.
  4. Programiz: C Programming Examples – Practical, worked-out C examples that reinforce key array operations and algorithms.
Scroll to Top