...

/

Count the Number of Occurrences of a Number in an Array

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 Function
int NoOfOccurrence(int array[], int size, int num)
{
int found = 0;
//base case
if (size< 0) //if the whole array has been traversed
return 0;
if (array[size] == num)// check if element is found
++found;// increment found
//recursive case
return (found + NoOfOccurrence(array, size- 1, num));
}
// Driver Function
int main() {
int array[7] = {2,3,4,1,7,8,3};//define an array
int size=7;//define the size of array
int num=3;// define the number whose frequency of occurrence is to be found
cout<<"Number of occurrences of "<<num<<" : ";
cout << NoOfOccurrence( array, size-1,num);//call recursive function
return 0;
}

Understanding the Code

A ...