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 functionint firstOccurrence(int array[], int size, int x, int currentIndex){//base caseif(size==currentIndex){//if array has been fully traversed and the element is not foundreturn -1;}if(array[currentIndex] == x){//if the value is found then return the indexreturn currentIndex;}//recursive casereturn firstOccurrence(array,size,x,currentIndex+1); //call the recursive function}//Driver functionint main(){int array[] = {2,3,4,1,7,8,3};//define an arrayint x = 3;//define the number whose first occurence is to be foundint size = 7;//define size of arraycout<<"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 ...