**Binary search program in c** is a simple and easy program element to find the given element in the set of sorted data.

**Searching Definition**

The searching is a process of finding the element in a data set of data.

**Binary search**

This is another method for finding an element in an array.

The condition for binary search is that all elements should be sorted we compare the element with the middle element of the array if it is less than a middle element then we search in a left portion of an array and if it is greater than the middle element then we search in the right portion of an array.

**Binary search example **

Suppose, the element searching is 49

Binary search

Iteration 1:-

Start=0 , end=9 , mid=start+end/2 (0+9/2=4)

Now the element at a position 4 is 25 compare this with 49 that is 49>25.

The middle element is smaller than finding element therefore our finding element is present in a right position of a array so set start to mid+1.

start= mid+1

=> start= 4+1

so start= 5

Iteration 2:-

In this, Start = 5 and end = 9

Find, mid= 5+9/2 =7

But, 49<57

In this case finding element is less than mid value, so we will find in left portion.

end = mid-1

= 7-1

= 6

Iteration 3:-

Start = 5 and end = 6

Find, mid= 5+6/2 = 5

But, 49>30

In this finding element is greater than middle element so we will find in right portion.

Start = mid+1

= 5+1

= 6

Iteration 4:-

Start = 6 and end = 6

mid= 6+6/2 = 6

6th is the position of 49 and it is mid value, We found the element 49 at 6 position in array.

## Binary search algorithm

- Declare variables. N, a[], start, end
- Take input size of array. N
- Take input array. a[N]
- Take a search element input. find
- Set start = 0 and end= last element
- Calculate a mid = (Start+end/2
- Traverse array

while start <= end

if a[mid] < find

Find an element in the second half

else if a[mid] == find

Print element found

break

else

Find an element in the first half

middle = (first + last)/2 - If start > end

Print number not found.

## Binary search program in c

#include <stdio.h> int main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements\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 in the list.\n", search); return 0; }

**Output:**