- Write a C program to count frequency of all array elements using for loop.
- How to find frequency of each elements in Array
Required Knowledge
- C printf and scanf functions
- For loop in C
- Accessing Array Elements in C
Algorithm to count frequency of each element in an array
Let inputArray is an integer array having N elements.
- We will declare another array countArray of same size as inputArray. We will use countArray to store the count of every array element and to keep track whether we had already counterd the frequency of current element or not(in case of duplicate elements in array).
- If countArray[i] == -1, it means we have not counted frequency of inputArray[i] yet and If countArray[i] == 0, it means we have already counted frequency of inputArray[i]
- Initialize each element of countArray to -1.
- Using a for loop, we will traverse inputArray from 0 to N-1. and count the frequency of every of every element.
- If countArray[i] == -1 for current element inputArray[i], then we store the frequency in countArray otherwise we don’t store as frequency for this element is already calculated.
C program to count frequency of each element of an array
/* * C Program to count frequency of each Array element */ #include <stdio.h> int main() { int inputArray[100], countArray[100]; int elementCount, i, j, count; printf("Enter Number of Elements in Array\n"); scanf("%d", &elementCount); printf("Enter %d numbers\n", elementCount); /* Read array elements */ for(i = 0; i < elementCount; i++){ scanf("%d", &inputArray[i]); countArray[i] = -1; } /* * for any element inputArray[i], If countArray[i] = -1, * that means frequency is not counted for this number yet * and countArray[i] = 0 means frequency is already * counted for this number. */ for(i = 0; i < elementCount; i++) { count = 1; for(j = i+1; j < elementCount; j++) { if(inputArray[i]==inputArray[j]) { countArray[j] = 0; count++; } } if(countArray[i]!=0) { countArray[i] = count; } } /* Print count of each element */ for(i = 0; i<elementCount; i++) { if(countArray[i] != 0) { printf("Element %d : Count %d\n", inputArray[i], countArray[i]); } } return 0; }
Output
Enter Number of Elements in Array 6 Enter 6 numbers 1 3 4 2 3 1 Element 1 : Count 2 Element 3 : Count 2 Element 4 : Count 1 Element 2 : Count 1