Would this code not work for finding last occurence

#include
using namespace std;
int last_occ(int *arr,int n,int key)
{
if(n==0)
{
return -1;
}
if(arr[n] == key)
{
return n;
}
last_occ(arr,n-1,key);
}

main()
{
int arr[] = {1,2,3,4,5,6,5,4,4,5,5};
int key = 4;
int n = sizeof(arr) / sizeof(int);
cout<<last_occ(arr,n,key);

}

hello @dhruvtrehan45
image
here u should use return statement.
ie return last_occ(arr,n-1,key);

also should compare arr[n-1] == key becuase n is indicating length .
rest everthing is correct in ur code.

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.