I am not able to get the correct output in lower bound case

#include
using namespace std;
int firstocc(int a[],int n,int key){

int s=0;
int e=6;
int ans;

	while(s<=e){

	int mid=(s+e)/2;

	if(a[mid]==key){

		ans=mid;
		e=mid-1;
	}

	else if(a[mid]>key){
		e=mid-1;
	}

	else{

		s=mid+1;
	}

	return ans;

}

return -1;

}
int main(){

int a[]={1,2,2,2,2,3,4};

int n=7;

int key;
cout<<"ENTER ELEMENT TO FIND IT'S FIRST OCCURENCE ";
cin>>key;

int k = firstocc(a,n,key);

if(k==-1){

	cout<<key<<"IS NOT PRESENT "<<endl;
}

else{

	cout<<"FIRST OCCURENCE OF "<<key<<" IS "<<k<<endl;
}

return 0;

}

Hey Abhigyan, initiailze ans with -1 and return ans outside the while loop otherwise your while loop will run only once. I have corrected your code you can refer this.

Thanks a lot Sir ! !