C Online Compiler
Example: Count Frequency with Direct Mapping in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Count Frequency with Direct Mapping #include
// Assuming max element value is less than 100 for this example. // For larger ranges, dynamically allocate or adjust MAX_VALUE. #define MAX_VALUE 100 int main() { // Step 1: Initialize the array and its size int arr[] = {10, 20, 20, 10, 10, 30, 40, 30, 5, 20, 5}; int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Declare and initialize the frequency array // Its size should be MAX_VALUE + 1 to accommodate elements up to MAX_VALUE int freq[MAX_VALUE] = {0}; // All elements initialized to 0 // Step 3: Iterate through the input array and increment counts for (int i = 0; i < n; i++) { // Check if element is within the valid range if (arr[i] >= 0 && arr[i] < MAX_VALUE) { freq[arr[i]]++; // Increment count for the element's value } else { printf("Warning: Element %d out of defined range [0, %d).\n", arr[i], MAX_VALUE); } } // Step 4: Print the frequencies of elements that appeared printf("Element | Frequency\n"); printf("--------|-----------\n"); for (int i = 0; i < MAX_VALUE; i++) { if (freq[i] > 0) { // Only print if the element appeared at least once printf("%7d | %9d\n", i, freq[i]); } } return 0; }
Output
Clear
ADVERTISEMENTS