Program Explanation
This C program counts the frequencies of elements in an integer array using a hash table (implemented as an array). The program uses a simple approach to hash the elements by using their values as indices in a frequency array. It assumes that the elements are non-negative integers.
Program Structure
- Include Headers: Necessary header files are included for standard input/output.
- Define Constants: A constant for the maximum size of the frequency array.
- Main Function: Contains the logic to input the array, count frequencies, and display results.
- Frequency Counting: A loop iterates through the input array, updating the frequency array based on the element values.
- Output: Finally, the program outputs the frequencies of each element present in the input array.
Code
#include
#define MAX 1000 // Maximum value of elements in the array
int main() {
int arr[MAX], freq[MAX] = {0}; // Initialize frequency array to 0
int n, i;
// Input size of the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Input elements of the array
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Count frequencies
for (i = 0; i < n; i++) {
freq[arr[i]]++; // Increment frequency of the element
}
// Display frequencies
printf("Element\tFrequency\n");
for (i = 0; i < MAX; i++) { if (freq[i] > 0) {
printf("%d\t%d\n", i, freq[i]);
}
}
return 0;
}
How to Compile and Run
- Open a terminal or command prompt.
- Copy the code into a file named
frequency_count.c
. - Compile the program using
gcc frequency_count.c -o frequency_count
. - Run the program using
./frequency_count
.
Example
Input:
Enter the number of elements in the array: 7
Enter 7 elements:
1 2 3 2 1 1 4
Output:
Element Frequency
1 3
2 2
3 1
4 1
Conclusion
This program demonstrates how to efficiently count the frequencies of elements in an array using hashing. The use of a frequency array allows for constant-time complexity for frequency counting, making it suitable for large datasets with known bounds on element values.