How to find the frequency of a number in C++
Finding the number of times a specific number occurs in a dataset may seem simple, but it forms the backbone of numerous algorithms and unlocks the potential for deeper analysis. Whether building intelligent systems or producing data-driven visualizations, a solid grasp of frequency counting will enable us to transform raw data into actionable knowledge.
In this Answer, we will use linear search to find the frequency of a number in C++.
How does linear search work?
Linear search, also known as sequential search, is a simple search algorithm to find a specific element within an array or a list. It works by sequentially checking each element in the dataset until the desired element is found. In our case, it will continue checking until it has traversed the entire dataset.
Start at the beginning: Linear search begins at the first element of the array.
Check each element: It checks each element in the array sequentially, comparing it against the target value. It continues to iterate through the entire array, incrementing the
frqcounter for each occurrence of the target value.
Code
The code for finding the frequency of a number is as follows:
#include <iostream>using namespace std;int findFreq(int arr[], int len, int target){int frq = 0;for (int i = 0; i < len; ++i){if (arr[i] == target){frq++;}}return frq;}int main(){int arr[] = { 2, 4, 5, 2, 6, 7, 2, 8, 2, 2, 2 };int target = 2;int len = sizeof(arr) / sizeof(arr[0]);int freq = findFreq(arr, len, target);cout << "The frequency of " << target << " is: " << freq << endl;return 0;}
Explanation
Line 4: The
findFreqfunction takes in three parameters: the arrayarr[], its lengthlen, and the target valuetargetwhose frequency needs to be determined.Line 6: This line initializes a variable
frqto store the frequency of thetargetvalue.Line 8: This line uses a
forloop to iterate through the array.Lines 9–14: Inside the loop, each element in the array is checked to see if it matches the
targetvalue. If there is a match, thefrqcounter is incremented.Line 16: The loop returns the determined frequency at the end.
Line 21: This line declares an array
arr[]containing integers.Line 23: This line sets the
targetvalue whose frequency needs to be found (in our case,target = 2).Line 24: This line calculates the length of the array
arr[]usingsizeof(arr) / sizeof(arr[0])and assigns it tolen.Line 26: This line calls the
findFreqfunction with the array, its length, and the target value. Stores the returned frequency in the variablefreq.Line 28: This line displays the frequency of the
targetvalue.
Time complexity
The time complexity of the provided code that implements linear search to find the frequency of a target number in an array is
Free Resources