Example: If elements of array are: 5, 10, 2, 5, 50, 5, 10, 1, 2, 2
Frequency of 5 = 3
Frequency of 10 = 2
Frequency of 2 = 3
Frequency of 50 = 1
Frequency of 1 = 1
Required knowledge:
Basic C programming, If else, For loop, ArrayProgram:
/**
* C program to count frequency of each element of array
*/
#include <stdio.h>
int main()
{
int arr[100], freq[100];
int size, i, j, count;
/*
* Read size of array and elements in array
*/
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
freq[i] = -1;
}
/*
* Counts frequency of each element
*/
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
if(arr[i]==arr[j])
{
count++;
freq[j] = 0;
}
}
if(freq[i]!=0)
{
freq[i] = count;
}
}
/*
* Prints frequency of each element
*/
printf("\nFrequency of all elements of array : \n");
for(i=0; i<size; i++)
{
if(freq[i]!=0)
{
printf("%d occurs %d times\n", arr[i], freq[i]);
}
}
return 0;
}
Output
Enter size of array: 10
Enter elements in array: 5 10 2 5 50 5 10 1 2 2
Frequency of all elements of array :
5 occurs 3 times
10 occurs 2 times
2 occurs 3 times
50 occurs 1 times
1 occurs 1 times
Enter elements in array: 5 10 2 5 50 5 10 1 2 2
Frequency of all elements of array :
5 occurs 3 times
10 occurs 2 times
2 occurs 3 times
50 occurs 1 times
1 occurs 1 times
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to count total number of notes in a given amount.
- C program to count total number of duplicate elements in an array.
- C program to count total number of negative elements in an array.
- C program to find all unique elements in an array.
- C program to find maximum and minimum elements in an array.
- C program to search an element in an array.
- C program to merge elements of two arrays.
- C program to sort elements of array in ascending order.
- C program to find reverse of any number.
- C program to check whether a number is palindrome or not.
- C program to find HCF of two numbers.
- C program to find LCM of two numbers.
- C program to add two matrices.
- C program to check Identity matrix.
- C program to find transpose of a matrix.
- C program to find determinant of a matrix.
- C program to print Pascal triangle up to n rows.