#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
- Include Headers: The program starts by including the standard input-output header (
<stdio.h>
). - Function Definition: The function
countFrequency
takes an array and its size as parameters. - Initialization:
- Two arrays,
freq
andcounted
, are declared.freq
will store the frequency of each element, whilecounted
will help track which elements have already been counted. - Both arrays are initialized to zero.
- Two arrays,
- 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.
- 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.