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++.
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 frq
counter for each occurrence of the target value.
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;}
Line 4: The findFreq
function takes in three parameters: the array arr[]
, its length len
, and the target value target
whose frequency needs to be determined.
Line 6: This line initializes a variable frq
to store the frequency of the target
value.
Line 8: This line uses a for
loop to iterate through the array.
Lines 9–14: Inside the loop, each element in the array is checked to see if it matches the target
value. If there is a match, the frq
counter 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 target
value whose frequency needs to be found (in our case, target = 2
).
Line 24: This line calculates the length of the array arr[]
using sizeof(arr) / sizeof(arr[0])
and assigns it to len
.
Line 26: This line calls the findFreq
function with the array, its length, and the target value. Stores the returned frequency in the variable freq
.
Line 28: This line displays the frequency of the target
value.
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