Skip to main content

Binary Search Example in C

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

About this program

This is an example program in c searching programs. Read the concept first: C Array, 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 Programs,C Array Examples */

#include<stdio.h>
#include<conio.h>

#define MAX_SIZE 5

int main() {
    int arr_search[MAX_SIZE], i,element;
	int f = 0, r =  MAX_SIZE, mid;
	
    printf("Simple Binary Search Example - Array\n");
    printf("\nEnter %d Elements for Searching : \n", MAX_SIZE);
    for (i = 0; i < MAX_SIZE; i++)
        scanf("%d", &arr_search[i]);

	printf("Enter Element to Search : ");
    scanf("%d", &element);
   

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

	  if (arr_search[mid] == element) {
         printf("\nSearch Element  : %d  : Found :  Position : %d.\n", element, mid+1);
         break;
	  }
      else if (arr_search[mid] < element)
         f = mid + 1;    
      else
         r = mid - 1;
   }
   
   if (f > r)
      printf("\nSearch Element : %d  : Not Found \n", element);
      
    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.

How It Works

This C program demonstrates Binary Search. It first reads the required values as input, then walks through the data with a loop to compute the result, and finally prints the output shown in the Sample Output above.

  1. Declare the variables that hold the program’s data.
  2. Read the input values that the program will work with.
  3. Iterate over the data using a loop to apply the logic.
  4. Use conditional statements to handle the different cases.
  5. Print the final result to the console so you can compare it with the sample output.

Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.

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 Binary Search, including the complete source code and the expected sample output.
How do I compile and run this C program?
Save the code in a `.c` file, compile it with `gcc filename.c -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