# C: Binary Search searches and finds but incorrect exit code

This code is finding all the numbers correctly. Only problem is it's throwing error of "\ expected an exit code of 1, not 0" when the number is not present. Help would be appreciated.

``````bool search(int value, int values[], int n)
{

int min = 0;
int max = n - 1;
int mid = (max + min) / 2;

if(n <= 0)
{
return false;
}
while (values[max] > values[min])
{
if (values[mid] == value)
{
return true;
}

else if (values[mid] > value)
{
return true;
}

else if (values[mid] < value)
{
return true;
}
else
{
return false;
}
}
return false;
}
``````

Modified code - exactly the same result - finds numbers but wrong exit code when int not present. I also tried removing the else statement but result was an endless loop. Removing final return statement didn't work either.

``````bool search(int value, int values[], int n)
{
int min = 0;
int max = n-1;
int mid = (max + min) / 2;

if(n <= 0)
{
return false;
}

while (values[max] >= values[min])
{
if (values[mid] == value)
{
return true;
}

else if (values[mid] > value) //value's on the left of mid
{
min = 0;
max = mid - 1;
return true;
}

else if (values[mid] < value) //value's on the right of mid
{
max = n-1;
min = mid + 1;
return true;
}

else
{
return false;
}

}
return false;
}
``````

Appropriate `while` loop would be `while (max >= min)`, looping as long as the search interval has elements.

If `values[mid] > value`, it means the value (if present) would be on the left, so set `max = mid - 1;`.

If `values[mid] < value`, it means the value (if present) would be on the right, so set `min = mid + 1;`.

The value is either equal, lower, or higher, so there are only three cases here. Might be different if you were using floating point, where one possible value is NAN (Not-A-Number).

Don't forget to recalculate `mid`, either at the beginning of each iteration, or after changing `min` or `max`.

• Thx, Blauelf: Your explanation helped me a lot. I've modified the code but I'm still getting the same result. Can you please look at the new code? Commented Mar 30, 2017 at 23:26

This code ended up solving the problem and tests successfully. The final 'else' statement was unnecessary. 'Mid' was re-calculated within the 'while' statement for each iteration. I also had to remove the array name from the 'while' statement. Thanks for helping, @Blauelf.

``````bool search(int value, int values[], int n)
int min = 0;
int max = n - 1;

while (min <= max)
{
int mid = (min + max) / 2;

if (values[mid] == value)
{
return true;
}

else if (value < values[mid]) //value's on the left of mid
{
max = mid - 1;
}

else if (value > values[mid]) //value's on the right of mid
{
min = mid + 1;
}
}
return false;
}
``````