Home >>Cpp Programs >C++ Program to find first occurrence of a Number Using Recursion in an array

# C++ Program to find first occurrence of a Number Using Recursion in an array

### 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:
• Step 1: Make a recursion function with inputs, and a variable currentIndex to traverse the input array.
• Step 2: If currentIndex == size of the input array then return -1.
• Step 3: If x == input[currentIndex] then return currentIndex.
• Step 4: Else, return the next call of recursive function with currentIndex incremented.
###### Example
``````
#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;
}
```
```
Output:
1