Last index element

#include<bits/stdc++.h>
using namespace std;
int lastOccurence(int arr[],int i,int key)
{
if(i==0)
return -1;
if(arr[i]==key)
return i;
return lastOccurence(arr,i–,key);
}
int main()
{
int n;
cin >> n;
int arr[n];
for(int i=0;i<n;i++) cin>>arr[i];
int key;
cin >> key;
int ans = lastOccurence(arr,n-1,key);

if(ans)
  cout<<ans<<endl;
else
  cout<<"-1"<<endl;
return 0;

}

where am i doing wrong

base case should be if(i<0){ return -1; }. key may be present at index=0;

yeah made that change.the code is getting compiled but no output is coming

@dare_devil_007
save your code at http://ide.codingblocks.com/ and then share here. I’ll check

https://ide.codingblocks.com/s/224908 there you go!!

@dare_devil_007
change “i–” in line 9 to “–i”. Your code will work.
Actually there is a difference between pre decrement and post decrement. Post decrement i.e i-- first uses the value of i and then decrement, so second argument of function always remains i. that’s why it is giving segmentation fault. Always use pre decrement in such case. pre decrement first decrease the value of i and then use it as function parameter.

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.