Skip to main content

Simple Binary Searching Program in C++

1 min read Updated June 30, 2026
Share:
On this page (6sections)

About this program

This is an example program in searching programs. Read the concept first: Understanding Array in C++, then study the code and output below.

Definition

Binary search is a quickest search algorithm that finds the position of a target value within a sorted array

Also Called,

  • half-interval search
  • logarithmic search
  • binary chop

Simple Binary Searching Program

/* Simple Binary Search Program Using Functions in C++*/
/* Data Structure C++ Programs,C++ Array Examples */

#include <iostream>
#include<conio.h>
#include<stdlib.h>

#define MAX_SIZE 5

using namespace std;

int main() {
    int arr_search[MAX_SIZE], i, element;
    int f = 0, r = MAX_SIZE, mid;

    cout << "Simple C++ Binary Search Example - Array\n";
    cout << "\nEnter " << MAX_SIZE << " Elements for Searching : " << endl;
    for (i = 0; i < MAX_SIZE; i++)
        cin >> arr_search[i];

    cout << "\nYour Data   :";
    for (i = 0; i < MAX_SIZE; i++) {
        cout << "\t" << arr_search[i];
    }

    cout << "\nEnter Element to Search : ";
    cin>>element;

    while (f <= r) {
        mid = (f + r) / 2;

        if (arr_search[mid] == element) {
            cout << "\nSearch Element  : " << element << " : Found :  Position : " << mid + 1 << ".\n";
            break;
        } else if (arr_search[mid] < element)
            f = mid + 1;
        else
            r = mid - 1;
    }

    if (f > r)
        cout << "\nSearch Element : " << element << "  : Not Found \n";

    getch();
}

Sample Output

Simple Binary Search Example - Array

Enter 5 Elements for Searching :
12
34
56
78
90
Enter Element to Search : 78

Search Element  : 78  : Found :  Position : 4.

Learn the concept first, then study the code:

Frequently Asked Questions

What does this C++ program do?
It is a C++ example program that demonstrates Simple Binary Searching, including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses loops to iterate over data, arrays and conditional logic, illustrating a common pattern in C++ programming.

Related Tutorials

Search tutorials