Finding last element (recursion)

#include
using namespace std;

int linear_search(int a[],int n,int m,int i){
int ans;
if(i==n){
return -1;
}
if(a[i]==m){
ans=i;
linear_search(a,n,m,i+1);
}
linear_search(a,n,m,i+1);
return ans;
}
int main(){
int n;
cin>>n;
int *a=new int[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int m;
cin>>m;
cout<<linear_search(a,n,m,0);
return 0;
}
why it is not correct?

@tishya_goyal please share the ide link of your code

1 Like

@tishya_goyal in your recursive function the variable ans is not local so it is everytime a new variable for every recursive function, if you want to access the same variable across all the recursive then you can make it static.
Also initialize it with -1 for case m is not present.

1 Like

okay!! i got it
thnx

@tishya_goyal Mark this doubt as resolved, if your doubt is solved.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.