#include <stdio.h>

void countFrequency(int arr[], int n) {
    int freq[n]; // Array to store frequencies
    int counted[n]; // Array to track counted elements
    int i, j;

    // Initialize frequency and counted arrays
    for (i = 0; i < n; i++) {
        freq[i] = 0;
        counted[i] = 0;
    }

    // Count frequency of each element
    for (i = 0; i < n; i++) {
        if (counted[i] == 0) { // Check if the element is counted
            freq[i] = 1; // Start counting this element
            for (j = i + 1; j < n; j++) {
                if (arr[i] == arr[j]) {
                    freq[i]++;
                    counted[j] = 1; // Mark as counted
                }
            }
        }
    }

    // Print frequencies
    printf("Element Frequency\n");
    for (i = 0; i < n; i++) {
        if (freq[i] > 0) { // Print only counted elements
            printf("%d         %d\n", arr[i], freq[i]);
        }
    }
}

int main() {
    int array[] = {10, 20, 10, 30, 20, 10, 40};
    int n = sizeof(array) / sizeof(array[0]);
    countFrequency(array, n);
    return 0;
}

Explanation

  1. Include Headers: The program starts by including the standard input-output header (<stdio.h>).
  2. Function Definition: The function countFrequency takes an array and its size as parameters.
  3. Initialization:
    • Two arrays, freq and counted, are declared. freq will store the frequency of each element, while counted will help track which elements have already been counted.
    • Both arrays are initialized to zero.
  4. Count Frequencies:
    • The outer loop iterates through each element of the array.
    • If an element hasn’t been counted yet (checked via the counted array), it initializes its frequency to 1.
    • The inner loop checks subsequent elements. If a match is found, it increments the frequency for that element and marks the matched element as counted.
  5. Print Results: After counting, the function prints the element and its frequency, ensuring that only counted elements are displayed.

Output

For the input array {10, 20, 10, 30, 20, 10, 40}, the output will be:

mathematicaCopy codeElement Frequency
10         3
20         2
30         1
40         1

This program effectively counts the frequency of each element in the array, achieving O(n²) time complexity due to the nested loops.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights