I was solving the question of “TO FIND LAST OCCURENCE OF THE NUMBER IN THE ARRAY” using recursion, and I’m getting -1 as my output always.
Here’s my code:
import java.util.*;
public class Main {
public static int findLastIndex(int[] arr, int x, int m)
{
if(x<0){
return -1;
}
if(arr[x]==m){
return x;
}else{
return findLastIndex(arr,x-1,m);
}
}
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int arr[]=new int[n];
int m = s.nextInt();
for(int i=0;i<n;i++){
arr[i]=s.nextInt();
}
int ans=findLastIndex(arr,n-1,m);
System.out.println(ans);
}
}