Search⌘ K

Find the First Occurrence of a Number in an Array

Understand how to implement a recursive method in Java to find the first occurrence of a specific number in an array. Learn to set base cases for stopping recursion and a recursive case to traverse the array through indexes. This lesson helps you build foundational recursion skills applied to arrays, useful for coding interviews.

First Occurrence of a Number

When given an array, find the first occurrence of a given number in that array and return the index of that number.

The following illustration explains how to approach this problem.

Implementing the Code

The following code explains how to find the first occurrence of a number in an array.

Experiment with the code by changing the values of array and num to see how it works!

Java
class ArrayClass {
private static int firstOccurrence(int[] a, int n, int currentIndex) {
if (a.length == currentIndex) {
return -1;
}
else if (a[currentIndex] == n) {
return currentIndex;
}
else {
return firstOccurrence(a, n, 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 num = 3;
int result = firstOccurrence(array, num, 0);
System.out.println("The first occurrence of the number " + num + " is at index: " + result);
}
}

Understanding the Code

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