Binary First Occ

int firstOcc(int *arr, int s, int e, int k){

int ans;

while(s<=e){
	int mid=(s+e)/2;

	if(arr[mid]==k){
		ans=mid;
		e=mid-1;
	}

	else if(arr[mid]<k){
		s=mid+1;
	}

	else{
		e=mid-1;
	}
}

return ans;

}

How to convert this into recursive code. Please give a step by step explanation (return type of function int) don’t copy paste from somewhere else.

@rachitbansal2500 https://ide.codingblocks.com/s/253537 let me know if you’re unable to understand anything

1 Like

Just one doubt, instead of returning the answer inside, when arr[mid]==k, can we return it at the end of the code?

And also, if we can how to go about it? since we’ve declared the currans and lowerans inside the if segment

@rachitbansal2500 yeah you can return it outside the if statement too, you’ll need to declare the variables outside the if statement, i dont think the code will need much editing to be able to do that.

Isn’t working please check: https://ide.codingblocks.com/s/253539
This is essentially why I was getting stuck.

@rachitbansal2500 see line 24 https://ide.codingblocks.com/s/253541

1 Like

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.