Last index find out using the recursive approach

I am trying to make the code myself in which i am checking the if there is only one element in the array and the element is equal to the search element then i return the index//base case . Anotherwise //recursively call made on the array of n-1.
// here is the code

// Guide me and give a gental approach to solve and build a logic recursive logic

@Vikaspal
Hello vikash,
there is a bug in your code-
a) you should return index even when n!=1 and arr[n-1]==key but in your code you are calling to smaller problem i.e n-1 for this case.

@Vikaspal
your function should look like this-

// Base case
if(n==1 ) { // suppose only one elements
if(a[n-1] == key) // if that element is equal to key
return n-1; // index of the find element
else // that only element is not equal to key so return -1
return -1;
}
// Recursive case ( case n>1)
if(a[n-1] != key){ // current element not equal to key so call to smaller problem
return lastIndex(a,n-1,key);;
}
else{ // current element is equal to key so return its index i.e n-1
return n-1;
}

if u have any doubt then please ask

thankyouso such much @aman212yadav bro I got the where i am doing wrong…
Can u suggest any another thing while solving the recursively problem.

1 Like

@Vikaspal
you are going in correct direction just practice more problems.

pls don’t forget to mark your doubt as resolved