Count the Number of Occurrences of a Number in an Array
This lesson will help you find the number of occurrences of a number in an array using recursion.
Total Occurrences of a Number
The number of occurrences of a number means the frequency by which a number n appears in the array.
The following illustration clears the concept:
Implementing the Code
The following code explains how to find the frequency of a number in an array using recursion.
Experiment with the code by changing the values of array
and num
to see how it works!
Press + to interact
#include<iostream>using namespace std;// Recursive Functionint NoOfOccurrence(int array[], int size, int num){int found = 0;//base caseif (size< 0) //if the whole array has been traversedreturn 0;if (array[size] == num)// check if element is found++found;// increment found//recursive casereturn (found + NoOfOccurrence(array, size- 1, num));}// Driver Functionint main() {int array[7] = {2,3,4,1,7,8,3};//define an arrayint size=7;//define the size of arrayint num=3;// define the number whose frequency of occurrence is to be foundcout<<"Number of occurrences of "<<num<<" : ";cout << NoOfOccurrence( array, size-1,num);//call recursive functionreturn 0;}
Understanding the Code
A ...