- How to find the frequency of each element in an array
- How to use a visited array to avoid counting duplicates
- How to display element-wise frequency counts
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to find the frequency or occurrence of each element in an array.
Finding the frequency of elements in an array is a common programming task. It is used in many real-world applications, such as:
- Finding the most frequent number in a dataset
- Analyzing survey responses
- Counting word occurrences in text processing
- Identifying duplicate values in a list
š” Key Point: Frequency of an element is the number of times it appears in the array. To avoid counting the same element multiple times, we use a visited array to mark elements that have already been counted.
C Program to Find Frequency of Each Element in Array
#include <stdio.h>
int main() {
int n, i, j;
int count;
// Ask user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare array of size n
int arr[n];
// Declare visited array to track counted elements
int visited[n];
// Initialize visited array with 0
for(i = 0; i < n; i++) {
visited[i] = 0;
}
// Read elements into the array
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Find frequency of each element
printf("\nFrequency of each element:\n");
for(i = 0; i < n; i++) {
// Skip if element is already counted
if(visited[i] == 1) {
continue;
}
count = 1;
for(j = i + 1; j < n; j++) {
if(arr[i] == arr[j]) {
count++;
visited[j] = 1; // Mark as visited
}
}
printf("%d occurs %d times\n", arr[i], count);
}
return 0;
}
Sample Output
Enter the number of elements: 8 Enter 8 elements: 10 20 30 10 20 10 40 30 Frequency of each element: 10 occurs 3 times 20 occurs 2 times 30 occurs 2 times 40 occurs 1 times
Another Example:
Enter the number of elements: 6 Enter 6 elements: 5 5 5 5 5 5 Frequency of each element: 5 occurs 6 times
Example with Negative Numbers:
Enter the number of elements: 7 Enter 7 elements: -5 10 -5 20 -5 10 30 Frequency of each element: -5 occurs 3 times 10 occurs 2 times 20 occurs 1 times 30 occurs 1 times
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int n;ā stores the number of elementsint i, j;ā loop countersint count;ā stores the frequency of each element
- Declare Arrays:
int arr[n];ā the main arrayint visited[n];ā keeps track of elements that have already been counted
- Initialize Visited Array: The
forloop sets all elements ofvisitedto 0 (not counted yet). - Get User Input: Prompts the user to enter the number of elements and then reads them into the array.
- Find Frequency: The outer loop
for(i = 0; i < n; i++)iterates through each element:- If
visited[i] == 1, the element has already been counted, so skip it. - Otherwise, set
count = 1and comparearr[i]with all later elements using the inner loop. - If a match is found, increment
countand markvisited[j] = 1.
- If
- Display Result: Prints each unique element and its frequency.
- Return:
return 0;indicates successful program execution.
š Why Use a Visited Array? Without a visited array, the program would print the frequency of duplicate elements multiple times. For example, if 10 appears three times, it would print "10 occurs 3 times" three times. The visited array ensures each element is printed only once.
Algorithm to Find Frequency of Elements
- Start
- Read the number of elements (n)
- Read n elements into the array arr
- Initialize visited array with 0
- For
i = 0ton-1:- If
visited[i] == 0:- Set
count = 1 - For
j = i+1ton-1:- If
arr[i] == arr[j]:count++- Set
visited[j] = 1
- If
- Print
arr[i]andcount
- Set
- If
- End
Alternative Method: Using Sorting
Another approach to find frequency is to sort the array first, then count consecutive equal elements. This method can be more efficient for large arrays.
#include <stdio.h>
int main() {
int n, i, j, count;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Simple bubble sort to sort the array
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-i-1; j++) {
if(arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Count frequency of each element
printf("\nFrequency of each element:\n");
for(i = 0; i < n; i = i + count) {
count = 1;
for(j = i + 1; j < n && arr[j] == arr[i]; j++) {
count++;
}
printf("%d occurs %d times\n", arr[i], count);
}
return 0;
}
š» Practice Exercise
Challenge 1: Modify the program to find and display only the most frequent element in the array.
Challenge 2: Find the unique elements (elements that appear exactly once) in the array.
š Click to Show Solution for Challenge 1
#include <stdio.h>
int main() {
int n, i, j;
int max_freq = 0, most_frequent_element;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
int visited[n];
for(i = 0; i < n; i++) {
visited[i] = 0;
}
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for(i = 0; i < n; i++) {
if(visited[i] == 1) {
continue;
}
int count = 1;
for(j = i + 1; j < n; j++) {
if(arr[i] == arr[j]) {
count++;
visited[j] = 1;
}
}
if(count > max_freq) {
max_freq = count;
most_frequent_element = arr[i];
}
}
printf("\nMost frequent element: %d (appears %d times)\n",
most_frequent_element, max_freq);
return 0;
}
Frequently Asked Questions
1. How do you find the frequency of elements in an array in C?
Use a visited array to track counted elements. For each unvisited element, count how many times it appears by comparing it with all other elements. Display the element and its count.
2. Why do we need a visited array?
Without a visited array, duplicate elements would be printed multiple times. The visited array ensures that each element is counted and printed only once.
3. What is the time complexity of this approach?
The time complexity is O(n²) because we use nested loops to compare each element with every other element. The space complexity is O(n) for the visited array.
4. Is there a faster way to find frequency?
Yes, you can sort the array first and then count consecutive equal elements. This has a time complexity of O(n log n) due to sorting. For integer ranges with limited values, you can also use a hash table or frequency array.
5. How can I find the frequency of a specific element?
Simply iterate through the array and count how many times that specific element appears. You don't need a visited array for a single element.
š” Tip: For large arrays with a small range of values, consider using a frequency array where the index represents the value and the value at that index represents the frequency.