Home >>Cpp Programs >C++ program to find Last occurrence of a Number using Recursion in an array
In this example, we will see a C++ program through which we can find the last occurrence of a number in an array.
In this program, we will start traversing the given array from 0, not from (N - 1), and indexing in the array starts from 0.
Program:
#include <bits/stdc++.h>
using namespace std;
int lastIndex(int input[], int size, int x, int currIndex){
if(currIndex== size){
return -1;
}
int index = lastIndex(input,size,x,currIndex+1);
if(index == -1 && input[currIndex] == x){
return currIndex;
}
else{
return index;
}
}
int main(){
int input[] = {10,9,8,9,6,9,4,3};
int x = 9;
int size = 10;
cout<<lastIndex(input,size,x,0);
return 0;
}