Find frequency of each element in an array
C program to find frequency of each element in one dimensional array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void frequency(int a[MAX], int freq[MAX], int n)
{
int i, j, count;
for(i=0;i<n;i++)
{
freq[i] = -1;
}
for(i=0;i<n;i++)
{
count = 1;
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
count++;
freq[j] = 0;;
}
}
if(freq[i] != 0)
{
freq[i] = count;
}
}
printf("\nFrequency of all the elements of the array:\n");
for(i=0;i<n;i++)
{
if(freq[i] != 0)
{
printf("%d occurs %d times\n",a[i], freq[i]);
}
}
}
void main()
{
int arr[MAX], freq[MAX];
int i, n;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
frequency(arr, freq, n);
getch();
}
Output
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :1
Element 2 :2
Element 3 :3
Element 4 :2
Element 5 :1
Element 6 :4
Element 7 :2
Element 8 :4
Frequency of all the elements of the array:
1 occurs 2 times
2 occurs 3 times
3 occurs 1 times
4 occurs 2 times