# C++ program for binary search

In this example, you will learn a c++ program to implement a binary search algorithm. This program finds the position of the target value within the sorted array list.

### How does Binary search work?

In binary search, elements are searched from the middle of an array. It is applicable only on sorted arrays even in ascending or descending order.  If the array list is not sorted the first task is to sort it. Let’s look at an example below.

### Prerequisite

To understand this example perfectly you should have the following C++ programming knowledge.

## Program: Binary Search

``````//C++ program for binary search
#include<iostream>
using namespace std;
int main()
{
int totalNum, x,first, last, middle, arraylist, searchNum;
cout<<"Enter Maximum number size: ";
cin>>totalNum;
cout<<"Enter all the numbers:"<<endl;
for (x=0; x<totalNum; x++)
{
cin>>arraylist[x];
}
cout<<"Search number from the list: ";
cin>>searchNum;
first = 0;
last = totalNum-1;
middle = (first+last)/2;
while (first <= last)
{
if(arraylist[middle] < searchNum)
{
first = middle + 1;
}
else if(arraylist[middle] == searchNum)
{
cout<<searchNum<<" Found at the list.";
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
}
return 0;
}``````

### Output

``````Enter Maximum number size: 7
Enter all the numbers:
11
17
18
45
50
71
95
Search number from the list: 5