Find the First Occurrence of a Number in an Array
This lesson will teach you how to find the first occurrence of a number in an array using recursion.
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!
Press + to interact
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 ...