Step 1: To solve this using recursion, make a recursion function with inputs, and a variable currIndex to traverse the input array.
Step 2: Base Case: If currIndex == size of the input array, return -1, i.e element not found.
Step 3: If x == input[currIndex], then return currIndex.
Step 4: else return the next call of recursive function with currIndex incremented.
C++ Source Code/Function:
#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};
int x = 8;
int size = 4;
cout<<firstIndex(input,size,x,0);
return 0;
}
Algorithm:
Step 1: To solve this using recursion, make a recursion function with inputs, and a variable currIndex to traverse the input array.
Step 2: Base Case: If currIndex == size of the input array, return -1, i.e element not found.
Step 3: If x == input[currIndex], then return currIndex.
Step 4: else return the next call of recursive function with currIndex incremented.
C++ Source Code/Function:
Output