1. ## Binary Search Algo

My Code is'nt able to find the index value if the 1st or the 2nd element of the array is checked for. Here's my code.
Also i want to exit on pressing 'x' For now, I'm using -1 to exit.

Code:
```#include<iostream>
#include<ctype.h>
using namespace std;
int main()
{
int arr[] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95};
int value;
for(int i = 0; i < 23; i++)
cout << arr[i] << " ";
cout << endl;
while(1)
{
cout << "Enter seach value(-1 to exit): ";
cin >> value;
if(value == -1)
{
cout << "Exiting..\n";
break;
}
int beg = 0;
int end = 23;
for(beg = 0; beg < 23; beg++)
{
int middle = (beg+end)/2;
if(value == arr[middle])
{
cout << "Its at location " << middle << endl;
break;
}
else if(value > arr[middle])
end = middle + 1;
else if(value < arr[middle])
end = middle - 1;
else
}
}
}```
Thanks,
--Sid

2. You're completely missing your indentation here. For reference, this is how you indent code:
Code:
```#include<iostream>
#include<ctype.h>
using namespace std;
int main()
{
int arr[] = {1, 4, 5, 6, 9, 14, 21, 23, 28, 31, 35, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95};
int value;
for(int i = 0; i < 23; i++)
cout << arr[i] << " ";
cout << endl;
while(1)
{
cout << "Enter seach value(-1 to exit): ";
cin >> value;
if(value == -1)
{
cout << "Exiting..\n";
break;
}
int beg = 0;
int end = 23;
for(beg = 0; beg < 23; beg++)
{
int middle = (beg+end)/2;
if(value == arr[middle])
{
cout << "Its at location " << middle << endl;
break;
}
else if(value > arr[middle])
end = middle + 1;
else if(value < arr[middle])
end = middle - 1;
else
}
}
}```

A binary search does not involve a loop over all items, so looping form 0 to 23 means it is not a binary search. It's like a mashup of linear search and binary search, and consequently does not work as either.

Having said that, it can be fixed by changing two lines. I'm not telling which two yet.
Fix up some other things first...
That magic number 23 has to go. instead use sizeof(arr)/sizeof(arr[0]). That calcuates the size of the whole array divide by the size of one item, giving the total number of items.

Lines 34 and 35 are a waste of time. How can value be not equal to arr[middle], but also not less than it and not greater than it?

4. Thanks for your reply Sir. Indentation was fine before pasting it here.
So my logic is terribly wrong?!! Maybe I should slow down my learning speed. Can you please recommend any good book to learn C++ from?

5. Originally Posted by Sid_TheBeginner
So my logic is terribly wrong?!!
There is right and wrong to consider, no middle ground.
Try understanding the logic first, and the code will automatically be correct (apart from syntax errors, which are easily corrected).

Can you please recommend any good book to learn C++ from?
C++ Book Recommendations
The Definitive C++ Book Guide and List - Stack Overflow