When I Run my code And take input of array in ascending order from user the function which i have made runs and if the i search the middle number from array to find its location the code runs perfectly fine. But when i search the number from array which is not middle the code does not give me any output please fix this issue.
#include<iostream>
using namespace std;
void input_array(int arr[], int n);
int binary_search(int arr[], int n, int target);
int main()
{
int limit;
cout<<"Enter The Limit For An Array:- ";
cin>>limit;
int arr[limit];
input_array(arr, limit);
int target;
cout<<"Enter The Number to find its position:- ";
cin>>target;
binary_search(arr, limit, target);
}
void input_array(int arr[], int n)
{
cout<<"Enter The Number in Increasing Order "<<endl;
for (int i = 0; i < n; i++)
{
cout<<i+1<<". Enter Number :- ";
cin>>arr[i];
}
}
int binary_search(int arr[], int n, int target)
{
int low = 0;
int high = n-1;
int mid;
for (int i = 0; i < n; i++)
{
mid = (low+high) / 2;
if (arr[mid] == target)
{
cout<<"The Position of The Given Target is :- "<<mid;
return 0;
}
if (arr[mid] > target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
i have created a program which is not working i dont know the reason why its not working kindly please solve my issue so i can proceed further.