Binary Search - Can't submit

Here is the code. I can’t submit it, probably some runtime error.

#include
using namespace std;

int b_search(int a[], int n, int key)
{
int beg = 0;
int last = n-1;

int mid = (beg+last)/2;

while(beg != last)
{
    if(a[mid] == key)
    {
        return mid;
    }
    else if(a[mid] > key)
    {
        last = mid;
    }
    else if(a[mid] < key)
    {
        beg = mid;
    }
}

return -1;

}

int main()
{
int n;
cin>>n;

int a[n];

for(int i=0; i<n; i++)
{
    cin>>a[i];
}

int key;
cin>>key;

int ans = b_search(a,n,key);

cout<<ans;

}

@abhishekchoudhary


Check it now. I have corrected some mistakes.

Got it.
It works now.
Thanks.

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.