...

/

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 teach you how to find the number of occurrences of a particular number in an array using recursion.

Total Occurrences of a Number

The number of occurrences of a number means the frequency a number n appears in the array.

The following illustration explains 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!

import java.io.*;
class ArrayClass {
private static int noOfOccurrences(int[] a, int key, int currentIndex) {
if (a.length == currentIndex) {
return 0;
}
else if (a[currentIndex] == key) {
return 1 + noOfOccurrences(a, key, currentIndex+1);
}
else {
return noOfOccurrences(a, key, currentIndex+1);
}
}
public static void main(String[] args) {
System.out.print("{");
int[] array = {2,3,4,1,7,8,3};
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println("}");
int key = 3;
int output = noOfOccurrences(array, key, 0);
System.out.println("Number of occurrences of " + key + ": " + output);
}
}

Understanding the Code

The code snippet above can be broken down into two parts. The recursive method and ...