Binary Search in C++

For the binary search program in C++, if the array values are not defined already then it will ask the user first to enter the size of the array. Then the user will enter array elements one by one. After adding all the elements to array ask the user to enter the element to search in an array by using the binary search.

In binary search all the array elements must be sorted already, otherwise, we will need to sort them first. If the duplicate numbers are entered by the user then there is no guarantee which element will be found in the binary search.

The program first checks whether the element is present at middle if not then the element will be compared with middle value if results greater then it is present in left sub-array otherwise present in right sub-array.

Program Example

Implementing the binary search in C++:

Following is the C++ program in which binary search is implemented

#include <iostream>
using namespace std;

int main()
int count, j, elements[50], search_num, first, last, mid;
cout<<"Enter the total number of elements :";

cout<<"\nEnter ">>count>>" numbers:\n";
for (j=0; j<count; j++)

cout<<"\nWhich number that you want to search: ";
first = 0;

last = count-1;
mid = (first+last)/2;

// binary search
while (first <= last)
if(elements[mid] < search_num){
first = mid + 1;

else if(elements[mid] == search_num){
cout<<search_num<<" found in array at "<<mid+1<<"\n";
else {
last = mid - 1;

mid = (first + last)/2;

if(first > last){
cout<<search_num<<" Not found in an array";
return 0;

The output should be:

Enter the total number of elements: 5
Enter 5 numbers:
Which number that you want to search: 45
45 Not found in an array
55 found in the array at  3