...

/

Find the First Occurrence of a Number in an Array

Find the First Occurrence of a Number in an Array

This lesson will help you find the first occurrence of a number in an array using recursion.

First Occurrence of a Number

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

The following illustration shows how to do it:

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 x to see how it works!

Press + to interact
#include<iostream>
using namespace std;
// Recursive function
int firstOccurrence(int array[], int size, int x, int currentIndex){
//base case
if(size==currentIndex){//if array has been fully traversed and the element is not found
return -1;
}
if(array[currentIndex] == x){//if the value is found then return the index
return currentIndex;
}
//recursive case
return firstOccurrence(array,size,x,currentIndex+1); //call the recursive function
}
//Driver function
int main(){
int array[] = {2,3,4,1,7,8,3};//define an array
int x = 3;//define the number whose first occurence is to be found
int size = 7;//define size of array
cout<<"First Occurence of the number "<<x<<" is at index:";
cout<<firstOccurrence(array,size,x,0);
return 0;
}

Understanding the Code

A recursive code can be broken down into two parts. The ...