For the binary search program in C Programming if the array values are not defined already it will ask the user first to enter the size of the array. Then the user will enter array elements one by one. After adding all the elements to array ask the user to enter the element to search in an array by using binary search.

It is required in binary search that all elements are in sorted form, otherwise, we should sort them first. If the user enters duplicate numbers, then there is no guarantee which element will be found in the binary search.

The program first checks whether the element present at middle, if not then the element going to compare with middle value. If results greater then the element to search present in left sub-array otherwise present in right sub-array.

## Program Example

### Implementing binary search in C:

Following C programs illustrates implementation of binary search.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include using namespace std; int main() { int count, j, elements[50], search_num, first, last, mid; cout<<"Enter the total number of elements :"; cin>>count; for (j=0; j<count; j++) { cout<<"Enter number "<<(j+1)<<": "; cin>>elements[j]; } cout<<"Which number that you want to search:"; cin>>search_num; first = 0; last = count-1; mid = (first+last)/2; while (first <= last) { if(elements[mid] < search_num){ first = mid + 1; } else if(elements[mid] == search_num){ cout<<search_num<<" found in array at "<<mid+1<<"\n"; break; } else { last = mid - 1; } mid = (first + last)/2; } if(first > last){ cout<<search_num<<" Not found in array"; } return 0; } |

The output should be:

5

Enter total 5 integer values :

10

15

16

29

30

Enter the value to find :

29

29 found at index 3