In this tutorial you will learn about the Count Frequency of each Element in an Array and its application with practical example.
C example to Count the frequency of each Element in an Array
In this tutorial, we will learn to create a C program that will Count the Frequency of each Element in an Array using C programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C programming.
- Arithmetic operations in C Programming.
Program to Count Frequency of each Element in an Array.
In this program, we will count the frequency of each element in the array. The frequency means the occurrence of the element in that array.
In this tutorial, we will first initialize the array. After that, we will find the length of the array. Then we will count the frequency of every element in the array. At last, we will print the frequency of each element to the user.
With the help of this program, we can Count the Frequency of each Element in an Array.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
/* C Program to Count Frequency of each Element in an Array */ #include <stdio.h> int main() { //Declaring the required variables for the program int arr[] = {1, 2, 8, 3, 2, 2, 2, 5, 1}; //arr[] = it will hold the array elements. //i = it will hold the integer value for the controlling of loop. //j = it will hold the integer value for the controlling of child loop. //Calculate length of array arr int length = sizeof(arr)/sizeof(arr[0]); //Array fr will store frequencies of element int fr[length]; int visited = -1; for(int i = 0; i < length; i++){ int count = 1; for(int j = i+1; j < length; j++){ if(arr[i] == arr[j]){ count++; //To avoid counting same element again fr[j] = visited; } } if(fr[i] != visited) fr[i] = count; } //Displays the frequency of each element present in array printf("---------------------\n"); printf(" Element | Frequency\n"); printf("---------------------\n"); for(int i = 0; i < length; i++){ //printing the array and its frequency. if(fr[i] != visited){ printf(" %d", arr[i]); printf(" | "); printf(" %d\n", fr[i]); } } printf("---------------------\n"); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- arr[] = it will hold the integer value.
- i = it will hold the integer value.
- j = it will hold the integer value.
Calculating the size of the array.
Program Logic Code.
Printing output of the program.