In: Computer Science
C LANGUAGE ONLY
Write a C program to count the frequency of each element in an array. Enter the number of elements to be stored in the array: 3 Input 3 elements of the array: element [0]: 25 element [1]: 12 element [2]: 43 Expected output: The frequency of all elements of an array: 25 occurs 1 times 12 occurs 1 times 3 occurs 1 times
#include <stdio.h>
int main()
{
//variable declaration
int num, temp, count, flag;
//get user input
printf("Enter the number of elements to be stored in the array:
");
scanf("%d", &num);
//declare array
int arr[num];
//get the array element
printf("Input 3 elements of the array:\n");
for(int i=0; i<num; i++)
{
printf("element [%d]: ", i);
scanf("%d", &arr[i]);
}
//display the frequency of elements of the array
printf("\nThe frequency of all elements of an array:\n");
for(int i=0; i<num; i++)
{
temp = arr[i];
count = 0;
flag = 0;
for(int j=0; j<i; j++)
{
if(temp==arr[j])
{
flag = 1;
break;
}
}
if(!flag)
{
for(int j=i; j<num; j++)
{
if(temp==arr[j])
count++;
}
printf("%d occurs %d times\n", temp, count);
}
}
return 0;
}
OUTPUT:
Enter the number of elements to be stored in the array: 3
Input 3 elements of the array:
element [0]: 25
element [1]: 12
element [2]: 43
The frequency of all elements of an array:
25 occurs 1 times
12 occurs 1 times
43 occurs 1 times