Home » C Programs » Binary Search Program in C

In a sorted list, binary search is a quick way to find a specific item. It operates by halving the portion of the list that can hold the item until only one viable spot remains. Binary search is a rapid approach to find an element in a sorted array, similar to looking up a word in a dictionary.

Binary search, in its most basic form, is used to quickly locate a value in a sorted sequence. For the sake of clarity, we’ll refer to the desired value as the target value. The target value is always found in a continuous subsequence of the starting sequence in binary search.

```
//Binary Search Program in C
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter the numbers\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present here\n", search);
}
```

Output

Enter the numbers

5

Enter 5 integers

45

33

56

78

99

Enter value to find

45

45 found at location 1