When working with arrays in C, one common problem is to identify which element occurs the most times. This element is called the most frequent element or the mode of the array. For example, in the array {1, 2, 3, 2, 4, 2}
, the number 2
appears three times, which is more than any other number, so the most frequent element is 2
.
This problem is important because it teaches you how to analyze data stored in arrays, work with nested loops, and apply logical conditions. It also connects directly to real-world scenarios such as analyzing survey results, detecting common errors in logs, or processing sensor readings.
In this tutorial, we will write C programs to find the most frequent element in an array. We will first use a simple nested loop approach, and then show a more efficient method using frequency arrays. Each example will be explained in detail so that you fully understand how it works.
Understanding the Problem
The task is simple: traverse the array, count how many times each element appears, and then identify the one with the maximum count. For example, in the array {5, 1, 5, 2, 3, 5, 2}
, 5
appears 3 times, 1
appears 1 time, 2
appears 2 times, 3
appears 1 time, and the most frequent element is 5
.
Program 1: Using Nested Loops
This approach compares each element with all others and keeps track of the highest frequency found.
#include <stdio.h>
int main() {
int n, i, j, count, maxCount = 0, mostFrequent;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for(i = 0; i < n; i++) {
count = 1;
for(j = i + 1; j < n; j++) {
if(arr[i] == arr[j]) {
count++;
}
}
if(count > maxCount) {
maxCount = count;
mostFrequent = arr[i];
}
}
printf("The most frequent element is %d, occurring %d times.\n", mostFrequent, maxCount);
return 0;
}
In this program, we first take input for the size of the array and then store the elements. The outer loop selects each element one by one, and the inner loop counts how many times that element occurs in the rest of the array. If the count for the current element is greater than the maximum count found so far, we update both maxCount
and mostFrequent
.
Finally, the program prints the element that appeared the most, along with the number of times it occurred.
This method is easy to understand, but it has a time complexity of O(n²) because of the nested loops, which can be slow for large arrays.
Program 2: Using a Frequency Array
If the elements are within a known range, we can use an auxiliary array (frequency array) to store counts more efficiently.
#include <stdio.h>
int main() {
int n, i, mostFrequent, maxCount = 0;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int freq[1000] = {0}; // assuming elements are less than 1000
for(i = 0; i < n; i++) {
freq[arr[i]]++;
if(freq[arr[i]] > maxCount) {
maxCount = freq[arr[i]];
mostFrequent = arr[i];
}
}
printf("The most frequent element is %d, occurring %d times.\n", mostFrequent, maxCount);
return 0;
}
Here, the program uses an array freq[]
to count how many times each element appears. Each index in freq
corresponds to a possible element in the input array. Every time we read an element, we increment its count in freq[]
. At the same time, we keep track of the element with the maximum frequency.
This approach is much faster with a time complexity of O(n), but it requires knowing the maximum possible element in advance, since the frequency array must be large enough to hold counts for all possible values.
Program 3: Using Sorting and Counting
Another efficient approach is to sort the array first and then count consecutive occurrences.
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int n, i, count = 1, maxCount = 1, mostFrequent;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
qsort(arr, n, sizeof(int), compare);
mostFrequent = arr[0];
for(i = 1; i < n; i++) {
if(arr[i] == arr[i-1]) {
count++;
} else {
count = 1;
}
if(count > maxCount) {
maxCount = count;
mostFrequent = arr[i];
}
}
printf("The most frequent element is %d, occurring %d times.\n", mostFrequent, maxCount);
return 0;
}
In this program, we sort the array using qsort()
. Once sorted, identical elements are placed next to each other. We then traverse the sorted array and count consecutive duplicates. The element with the highest count is stored as the most frequent.
This method works well and has a time complexity of O(n log n) due to sorting.
FAQs
Q1: What if two elements occur with the same maximum frequency?
The program will print one of them. To handle ties, you can extend the logic to store all elements that share the maximum count.
Q2: Which method is best?
For small arrays, the nested loop is fine. For larger arrays with limited range of elements, the frequency array is fastest. For arrays with unknown range, the sorting method is a balanced choice.
Q3: Can this program handle negative numbers?
Yes, the nested loop and sorting approaches can handle negative numbers directly. For the frequency array approach, extra adjustments are needed since array indexes cannot be negative.
Conclusion
Finding the most frequent element in an array is an essential problem in C programming that introduces frequency counting, optimization, and sorting. The nested loop method is straightforward but slow. The frequency array method is fast but needs extra memory and assumptions about the range of numbers. Sorting and counting is a middle-ground solution that works in most cases.
Mastering these approaches will give you a strong foundation for working with arrays and analyzing data in C.
References & Additional Resources
A collection of standard books and trusted tutorials for learning arrays in C and solving frequency-related problems.
- Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988.
- GeeksforGeeks: How to Find the Mode of Numbers in an Array in C? ā Step-by-step explanation of finding the mode (most frequent element) in an array using hashing and traversal techniques.
- TutorialsPoint: Arrays in C ā Covers the fundamentals of arrays, including declaration, initialization, storage, and common operations in C.
- Programiz: C Array Examples ā A set of practical C examples that show how arrays are used in solving real problems.