Prime

#### Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

#### Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

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

## Program to count frequency of elements in an array

Now we will learn the program to find the frequency of each element of an array which is discussed here. Given an array, the task is to find the frequency of all the elements of the array.For example, consider the following array

Input:
arr = {1, 2, 3, 5, 2, 7, 3, 5}

Output:
1 occurs 1 times
2 occurs 2 times
3 occurs 2 times
5 occurs 2 times
7 occurs 1 times

## Algorithm

• Input the number of elements of an array.
• Input the array elements.
• Make the array unique. i.e new array with only distinct element.
• Count each time the element is present in the list.
• Print the frequency array which displays the frequency of all the elements of the array.
#include <stdio.h>
int main()
{
int n;
int i, j, count=0, unique = 0;;
scanf("%d",&n);
int array[n];
int newarray[n];
for(i=0; i<n; i++)
{
scanf("%d",&array[i]);
}
for(i=0; i<n; i++)
{
count = 0;
for(j=0;j<=i;j++)
{
if(array[i]==array[j])
{
count++;
}
}
if(count==1)
{
newarray[unique] = array[i];
unique++;
}
}
for(i=0; i<unique; i++)
{
count = 0;
for(j=0; j<n; j++)
{
if(newarray[i]==array[j])
{
count++;
}
}
printf("%d element is present %d times\n",array[i],count);
}
return 0;
}
8
1 2 3 5 2 7 3 5
1 element is present 1 times
2 element is present 2 times
3 element is present 2 times
5 element is present 2 times
7 element is present 1 times