Home >>Cpp Programs >C++ Program to find first occurrence of a Number Using Recursion in an array
In this example, we will see a C++ program through which we will find the first occurrence of a number in a given array.
Algorithm:
#include <bits/stdc++.h>
using namespace std;
int firstIndex(int input[], int size, int x, int currIndex){
if(size==currIndex){
return -1;
}
if(input[currIndex] == x){
return currIndex;
}
return firstIndex(input,size,x,currIndex+1);
}
int main(){
int input[] = {9,8,10,8,4,8,2,5,7,9,2,8};
int x = 8;
int size = 15;
cout<<firstIndex(input,size,x,0);
return 0;
}