In this tutorial we will learn writing C Program to find highest frequency element in array. Our program will print the array element which have repeated most times. There is one edge case where two elements might repeat same time. This type of case we are not handling in our code.
C Program to find highest frequency element in array
#include <stdio.h>
#include <stdbool.h>
int main() {
int size, i, j, count, maxCount = 0;
printf("**C Program to find highest frequency element(s) in array**\n");
printf("Enter the number of elements: ");
scanf("%d", &size);
int arr[size];
bool visited[size]; // To track if element was already counted
for(i = 0; i < size; i++) {
printf("Please give value for index %d: ", i);
scanf("%d", &arr[i]);
visited[i] = false;
}
// First pass to find maxCount
for(i = 0; i < size; i++) {
if(visited[i])
continue;
count = 1;
for(j = i + 1; j < size; j++) {
if(arr[j] == arr[i]) {
count++;
visited[j] = true; // Mark duplicate as visited
}
}
if(count > maxCount)
maxCount = count;
}
// Reset visited and print elements with maxCount
for(i = 0; i < size; i++)
visited[i] = false;
printf("Element(s) with maximum frequency (%d times):\n", maxCount);
for(i = 0; i < size; i++) {
if(visited[i])
continue;
count = 1;
for(j = i + 1; j < size; j++) {
if(arr[j] == arr[i]) {
count++;
visited[j] = true;
}
}
if(count == maxCount) {
printf("%d\n", arr[i]);
}
}
return 0;
}
Output
**C Program to find highest frequency element(s) in array**
Enter the number of elements: 6
Please give value for index 0: 3
Please give value for index 1: 1
Please give value for index 2: 3
Please give value for index 3: 2
Please give value for index 4: 1
Please give value for index 5: 2
Element(s) with maximum frequency (2 times):
3
1
2
What did you think?