C program to find the frequency of each element in the array

C program to find the frequency of elements in an array

Find the frequency of elements in an array

Here we will find the frequency of element in an given array. To count frequency of each element we require two loops. 

Lets  take an example to understand it clearly

For example:

Size of array: 6
Enter the elements: 9 7 5 9 6 3
The frequency of 9 is 2
The frequency of 7 is 1
The frequency of 5 is 1
The frequency of 6 is 1
The frequency of 3 is 1

C-program-to-find-the-frequency-of-elements-in-an-array

Algorithm

 

  • To  Find the frequency of elements in an array follow these steps.
  • Input the number of elements of an array.
  • Input the array elements.
  • Create another array to store the frequency of elements.
  • Traverse the input array and update the count of the elements in the frequency array.
  • Print the frequency array which displays the frequency of all the elements of the array.

C Code Based on above algorithm

#include 
int main()
{
int n, i, j, total;
int Array[60], Frequency[60];
//Taking the size of array as input

printf("Enter size of array: ");
scanf("%d", &n);
//Taking the elements of the array as a input from the user

printf("Enter elements: ");
for(i=0; i<n; i++)
{
scanf("%d", &Array[i]);
Frequency[i] = -1;
}
//Counting the frequency of each elements of the Array

for(i=0; i<n; i++)
{
total = 1;
for(j=i+1; j<n; j++)
{
if(Array[i]==Array[j])
{
total++;
Frequency[j] = 0;
}
}
if(Frequency[i] != 0)
{
Frequency[i] = total;
}
}
//Printing the frequency of elements in the array

for(i=0; i<n; i++)
{
if(Frequency[i] != 0)
{
printf("%d occurs %d times,", Array[i], Frequency[i]);
}
}
}

Output 

Enter size of array: 5
Enter elements: 1
1
2
3
4
1 occurs 2 times,
2 occurs 1 times,
3 occurs 1 times,
4 occurs 1 times,

Enter size of array: 8
Enter elements: 1
2
3
2
4
5
6
1
1 occurs 2 times,
2 occurs 2 times,
3 occurs 1 times,
4 occurs 1 times,
5 occurs 1 times,
6 occurs 1 times,