Finding the Frequency of Elements in an Array
Understanding Frequency Calculation
Finding the frequency of elements in an array involves counting how many times each element appears.
We will explore three different methods to determine element frequency using C.
Method 1: Using Nested Loops
This method iterates through the array and counts occurrences using nested loops.
#include <stdio.h> #define SIZE 10 void findFrequency(int arr[], int n) { int visited[SIZE] = {0}; for (int i = 0; i < n; i++) { if (visited[i] == 1) continue; int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { count++; visited[j] = 1; } } printf("%d appears %d times\n", arr[i], count); } } int main() { int arr[] = {1, 2, 2, 3, 4, 1, 5, 1, 3, 2}; int n = SIZE; findFrequency(arr, n); return 0; }
1 appears 3 times
2 appears 3 times
3 appears 2 times
4 appears 1 time
5 appears 1 time
Method 2: Using Sorting
This method sorts the array first and then counts the frequency.
#include <stdio.h> #include <stdlib.h> #define SIZE 10 int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } void findFrequency(int arr[], int n) { qsort(arr, n, sizeof(int), compare); int count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) { count++; } else { printf("%d appears %d times\n", arr[i - 1], count); count = 1; } } printf("%d appears %d times\n", arr[n - 1], count); } int main() { int arr[] = {1, 2, 2, 3, 4, 1, 5, 1, 3, 2}; int n = SIZE; findFrequency(arr, n); return 0; }
1 appears 3 times
2 appears 3 times
3 appears 2 times
4 appears 1 time
5 appears 1 time
Method 3: Using Hashing
This method uses a hash table (array) to store frequency counts.
#include <stdio.h> #define MAX 100 void findFrequency(int arr[], int n) { int freq[MAX] = {0}; for (int i = 0; i < n; i++) { freq[arr[i]]++; } for (int i = 0; i < MAX; i++) { if (freq[i] > 0) { printf("%d appears %d times\n", i, freq[i]); } } } int main() { int arr[] = {1, 2, 2, 3, 4, 1, 5, 1, 3, 2}; int n = 10; findFrequency(arr, n); return 0; }
1 appears 3 times
2 appears 3 times
3 appears 2 times
4 appears 1 time
5 appears 1 time