Suppose we have an array. There are n different elements. We have to check the frequency of one element in the array. Suppose A = [5, 12, 26, 5, 3, 4, 15, 5, 8, 4], if we try to find the frequency of 5, it will be 3.
To solve this, we will scan the array from left, if the element is the same as the given number, increase the counter, otherwise go for the next element, until the array is exhausted.
Example
#include<iostream>
using namespace std;
int countElementInArr(int arr[], int n, int e) {
int count = 0;
for(int i = 0; i<n; i++){
if(arr[i] == e)
count++;
}
return count;
}
int main () {
int arr[] = {5, 12, 26, 5, 3, 4, 15, 5, 8, 4};
int n = sizeof(arr)/sizeof(arr[0]);
int e = 5;
cout << "Frequency of " << e << " in the array is: " << countElementInArr(arr, n, e);
}Output
Frequency of 5 in the array is: 3