0
0
CProgramBeginner · 2 min read

C Program to Find Frequency of Elements

To find the frequency of elements in C, use two loops: the outer loop picks each element, and the inner loop counts how many times it appears, then print the element with its count using printf.
📋

Examples

InputArray: {1, 2, 2, 3, 1}
OutputElement 1 occurs 2 times Element 2 occurs 2 times Element 3 occurs 1 time
InputArray: {5, 5, 5, 5}
OutputElement 5 occurs 4 times
InputArray: {7}
OutputElement 7 occurs 1 time
🧠

How to Think About It

To find how many times each number appears, look at each number one by one. For each number, check the whole list to count how many times it shows up. Keep track of which numbers you already counted so you don't count them again.
📐

Algorithm

1
Get the size of the array and the array elements from the user.
2
Create a visited array to mark elements already counted.
3
For each element in the array, if it is not visited, count how many times it appears in the array.
4
Mark all occurrences of that element as visited.
5
Print the element and its frequency.
6
Repeat until all elements are processed.
💻

Code

c
#include <stdio.h>

int main() {
    int n, i, j, count;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    int arr[n], visited[n];

    printf("Enter elements:\n");
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        visited[i] = 0;
    }

    for(i = 0; i < n; i++) {
        if(visited[i] == 1) continue;
        count = 1;
        for(j = i + 1; j < n; j++) {
            if(arr[i] == arr[j]) {
                count++;
                visited[j] = 1;
            }
        }
        printf("Element %d occurs %d %s\n", arr[i], count, count > 1 ? "times" : "time");
    }
    return 0;
}
Output
Enter number of elements: 5 Enter elements: 1 2 2 3 1 Element 1 occurs 2 times Element 2 occurs 2 times Element 3 occurs 1 time
🔍

Dry Run

Let's trace the array {1, 2, 2, 3, 1} through the code

1

Input array and initialize visited

arr = {1, 2, 2, 3, 1}, visited = {0, 0, 0, 0, 0}

2

Check element at index 0 (1)

Count occurrences of 1: found at index 0 and 4, count = 2; mark visited[4] = 1

3

Check element at index 1 (2)

Count occurrences of 2: found at index 1 and 2, count = 2; mark visited[2] = 1

4

Check element at index 2

visited[2] = 1, skip counting

5

Check element at index 3 (3)

Count occurrences of 3: found only at index 3, count = 1

6

Check element at index 4

visited[4] = 1, skip counting

IndexElementVisitedCountAction
0102Counted and marked visited[4]
1202Counted and marked visited[2]
221-Skipped
3301Counted
411-Skipped
💡

Why This Works

Step 1: Mark visited elements

We use a visited array to remember which elements we already counted to avoid counting duplicates multiple times.

Step 2: Count frequency

For each unvisited element, we count how many times it appears by comparing it with the rest of the array.

Step 3: Print results

We print the element and its frequency, using singular or plural form based on the count.

🔄

Alternative Approaches

Using a hash map (if allowed)
c
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int key;
    int count;
    struct Node* next;
};

// Simple hash function and chaining omitted for brevity
// This approach uses extra memory but is faster for large arrays

int main() {
    int n, i;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    int arr[n];
    printf("Enter elements:\n");
    for(i = 0; i < n; i++) scanf("%d", &arr[i]);

    // Implementation would use a hash map to count frequencies
    printf("This method uses a hash map for faster counting but requires more memory.\n");
    return 0;
}
This method is faster for large data but requires more memory and more complex code.
Sorting the array first
c
#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    int n, i, count = 1;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    int arr[n];
    printf("Enter elements:\n");
    for(i = 0; i < n; i++) scanf("%d", &arr[i]);

    qsort(arr, n, sizeof(int), compare);

    for(i = 1; i <= n; i++) {
        if(i < n && arr[i] == arr[i-1]) {
            count++;
        } else {
            printf("Element %d occurs %d %s\n", arr[i-1], count, count > 1 ? "times" : "time");
            count = 1;
        }
    }
    return 0;
}
Sorting groups equal elements together, making counting simpler and faster but changes original order.

Complexity: O(n^2) time, O(n) space

Time Complexity

The program uses nested loops: the outer loop runs n times and the inner loop runs up to n times, resulting in O(n^2) time.

Space Complexity

An extra array of size n is used to track visited elements, so space complexity is O(n).

Which Approach is Fastest?

Using sorting or a hash map can reduce time complexity to O(n log n) or O(n), but may use more memory or complex code.

ApproachTimeSpaceBest For
Nested loops with visited arrayO(n^2)O(n)Small arrays, simple code
Sorting then countingO(n log n)O(1)When order doesn't matter
Hash map countingO(n)O(n)Large arrays, faster counting
💡
Use a visited array to avoid counting the same element multiple times.
⚠️
Beginners often forget to mark duplicates as visited, causing repeated counts.