- C Programming Examples
- C Programming Examples
- C Print Hello World
- C Get Input from User
- C Print Integer
- C Add Two Numbers
- C Add Subtract Multiply Divide
- C Add n Numbers
- C Area Perimeter of Square
- C Area Perimeter of Rectangle
- C Area Circum of Circle
- C Fahrenheit to Celsius
- C Celsius to Fahrenheit
- C Inches to Centimeters
- C Kilogram to Gram
- C Reverse a Number
- C Swap Two Numbers
- C Interchange Numbers
- C Print ASCII Value
- C Print Fibonacci Series
- C Check Palindrome or Not
- C Check Armstrong or Not
- C Find Armstrong Numbers
- C Find nCr and nPr
- C Find Profit Loss
- C Sum of their Square
- C First & Last Digit Sum
- C Sum of All Digit
- C Product of All Digit
- C Print Total Digit in Number
- C Check Perfect Number
- C Find Basic Gross Salary
- C Round Number to Integer
- C Print Series upto n Term
- C Find Factors of Number
- C if-else & Loop Programs
- C Check Even or Odd
- C Check Prime or Not
- C Check Alphabet or Not
- C Check Vowel or Not
- C Check Leap Year or Not
- C Is Reverse Equal Original
- C Make Calculator
- C Add Digits of Number
- Count Positive Negative Zero
- C Largest of Two Numbers
- C Largest of Three Numbers
- C Smallest of Two Numbers
- C Smallest of Three Numbers
- C Find Factorial of Number
- C Find LCM & HCF
- C Find LCM of n Numbers
- C Find HCF of n Numbers
- C Find Arithmetic Mean
- C Find Average, Percentage
- C Find Student Grade
- C Print Table of Number
- C Print Prime Numbers
- C Find Discount Purchase
- C Calculate Parcel Charge
- C Calculate Wage of Labor
- C Print Phone Bill
- C Conversion programs
- C Decimal to Binary
- C Decimal to Octal
- C Decimal to Hexadecimal
- C Binary to Decimal
- C Binary to Octal
- C Binary to Hexadecimal
- C Octal to Decimal
- C Octal to Binary
- C Octal to Hexadecimal
- C Hexadecimal to Decimal
- C Hexadecimal to Binary
- C Hexadecimal to Octal
- C Pattern Programs
- C Pattern Printing Programs
- C Print Diamond Pattern
- C Print Floyd's Triangle
- C Print Pascal's Triangle
- C Array Programs
- C 1D Array Programs
- C Linear Search
- C Binary Search
- C Largest Element in Array
- C Smallest Element in Array
- C Second Largest/Smallest
- C Count Even Odd
- C Array Element at Even
- C Array Element at Odd
- C Print Even Array Elements
- C Print Odd Array Elements
- C Sum/Product of Even/Odd
- C Reverse an Array
- C Insert Element in Array
- C Delete Element from Array
- C Merge Two Arrays
- C Bubble Sort
- C Selection Sort
- C Insertion Sort
- C Print Common Elements
- C 2D Array Programs
- C Add Two Matrices
- C Subtract Two Matrices
- C Transpose a Matrix
- C Multiply Two Matrices
- C Sum All Matrix Elements
- C Largest Element in Matrix
- C Print Row Column Total
- C 3D Array Programs
- C String Programs
- C Print String
- C Find Length of String
- C Compare Two String
- C Copy a String
- C Concatenate String
- C Reverse a String
- C Count Vowels Consonants
- C Replace Vowel in String
- C Delete Vowels from String
- C Delete Word from String
- C Frequency of Character
- C Count Word in String
- C Remove Spaces from String
- C Sort a String
- C Sort String in Alphabetical
- C Sort Words in Ascending
- C Sort Words in Descending
- C Uppercase to Lowercase
- C Lowercase to Uppercase
- C Swap Two Strings
- C Check Anagram or Not
- C Check Palindrome String
- C Print Number in Words
- C Print Successive Character
- C Character without Space
- C Remove Extra Spaces
- C File Programs
- C Read a File
- C Write Content to File
- C Read & Display File
- C Copy a File
- C Merge Two Files
- C Reverse File
- C Count All Character in File
- C List Files in Directory
- C Encrypt & Decrypt a File
- C Delete a File
- C Misc Programs
- Generate Random Numbers
- C Print Date Time
- C Print Message with Time
- C Get IP Address
- C Print Smiling face
- C Pass Array to Function
- Add Two Numbers using Pointer
- C Address of Variable
- C Shutdown Computer
- C Programming Tutorial
- C Tutorial
- C Programming Library
- C Standard Library
- C Programming Test
- C Programming Test
- Give Online Test
- All Test List

# C Program for Binary Search

In this article, you'll learn and get code about how to search an element from given array using binary search technique. But before going through the program, if you are not aware of how binary search works, then I recommend you to go through the step by step working of Binary search.

Here are the list of programs you will go through over here, with its step by step explanation:

- Binary Search without using Function
- Binary Search using Function
- Binary Search using Recursion

## Binary Search in C

This is the simplest program of binary search. Simplest in the sense, here we have directly asked from user to enter 10 element or numbers without giving to specify the size of array and then enter his/her required amount of element. Also the sorting code block is not included in this program. So I've just asked to enter already sorted array as input. Let's take a look at the program:

#include<stdio.h> #include<conio.h> int main() { int i, arr[10], search, first, last, middle; printf("Enter 10 elements (in ascending order): "); for(i=0; i<10; i++) scanf("%d", &arr[i]); printf("\nEnter element to be search: "); scanf("%d", &search); first = 0; last = 9; middle = (first+last)/2; while(first <= last) { if(arr[middle]<search) first = middle+1; else if(arr[middle]==search) { printf("\nThe number, %d found at Position %d", search, middle+1); break; } else last = middle-1; middle = (first+last)/2; } if(first>last) printf("\nThe number, %d is not found in given Array", search); getch(); return 0; }

This program was written under **Code::Blocks** IDE. Here is the initial snapshot of sample run:

Now provide any 10 elements in ascending order, say **1, 2, 3, 4, 5, 6, 7, 8, 9,** and **10** and then press **ENTER**
key. Again enter any element or number to be search say **7**, press **ENTER** key to see the output given in the snapshot here:

If user supply all the 10 numbers as entered in above output. But this time, when he/she entered any number say **15** to be
search from the given list of number, then here is the output you will see:

#### Program Explained

- Declare all the required variable say
**i, arr[], search, first, last, middle**of**int**(integer type) - Here
**arr[]**is declared of size 10 to store upto 10 elements or numbers - Now receive 10 numbers as input from user
- As indexing in an array starts from 0, so first element gets stored in
**arr[0]**, second element gets stored in**arr[1]**, and so on - Now ask to enter the number to be search and store it in
**search**variable - Now initialize
**0**to**first**(index), 9 to**last**(index), and find the value of**middle**(index) using**first+last/2** - Create a
**while**loop, that continue running until the value of**first**(index) becomes less than or equal to the value of last (index) - The meaning of above step is, process inside the loop continue running until the interval becomes zero, as told in the logic given at start of this article
- Inside the
**while**loop, first check whether value at middle index (**arr[middle]**) is less than**search**(number to be search) or not using**if**statement - If it is, then initialize
**middle+1**to**first**and go to the last statement of the loop, that is**middle = (first+last)/2** - If 9
^{th}step evaluates to be false, then follow further step given below - Now program flow goes to
**else-if**part and checks whether element at middle (**arr[middle]**) is equal to**search**(number to be search) or not - If it is equal, then print the position. Here we have added the index number by one to display the position of the
number. As indexing starts from 0. For example, in an array, there are 4 numbers say
**10, 20, 30, 40**. So, the index will be**0, 1, 2, 3**. But normally people knows like this:- 10 preset at first position
- 20 present at second position
- 30 present at third position
- 40 present at fourth position

- So i have added 1 to
**middle**and prints its value as the position of the given number in array - Now the program flow goes to the last statement of the
**while**loop, that is**middle = (first+last)/2;** - If 12
^{th}step evaluates to be false, then**else**block gets evaluated, and**middle-1**is assigned to**last**and continue running the loop until the condition of**while**loop evaluates to be false

Here is the modified version of binary search program (as given above) in C. Here we have leave the size of array to be decided by user at run-time. And before performing the binary search, bubble sort is used to sort the given array in ascending order.

**Important** - This program finds the position of number from sorted array, not from the actual array that is entered by user at
run-time. For example, if user supply **10, 50, 20, 30, 40** as array input, and **20** as number to be search. Then this program
sort the array, so the array becomes **10, 20, 30, 40, 50** and the position of **20** will be **2**.

#include<stdio.h> #include<conio.h> int main() { int i, j, n, arr[100], search, first, last, middle, temp; printf("How many element you want to store in array ? "); scanf("%d", &n); printf("\nEnter %d array elements: ", n); for(i=0; i<n; i++) scanf("%d", &arr[i]); printf("\nEnter element to be search: "); scanf("%d", &search); // sorting given array using bubble sort for(i=0; i<(n-1); i++) { for(j=0; j<(n-i-1); j++) { if(arr[j]>arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } // sort array printf("\nNow the sorted Array is:\n"); for(i=0; i<n; i++) printf("%d ", arr[i]); // back to binary search first = 0; last = n-1; middle = (first+last)/2; while(first <= last) { if(arr[middle]<search) first = middle+1; else if(arr[middle]==search) { printf("\n\nThe number, %d found at Position %d", search, middle+1); break; } else last = middle-1; middle = (first+last)/2; } if(first>last) printf("\nThe number, %d is not found in given Array", search); getch(); return 0; }

Here is the snapshot of sample run:

### Binary Search Program in C using User-defined Function

Now modify the first program of this article that does the same job but this time using function as shown in the program given below:

#include<stdio.h> #include<conio.h> int binarySearchFun(int arr[], int); int main() { int i, arr[10], search, pos; printf("Enter 10 elements (in ascending order): "); for(i=0; i<10; i++) scanf("%d", &arr[i]); printf("\nEnter element to be search: "); scanf("%d", &search); pos = binarySearchFun(arr, search); if(pos==0) printf("\nThe number, %d is not found in given Array", search); else printf("\nThe number, %d found at Position %d", search, pos); getch(); return 0; } int binarySearchFun(int arr[], int search) { int first, last, middle; first = 0; last = 9; middle = (first+last)/2; while(first <= last) { if(arr[middle]<search) first = middle+1; else if(arr[middle]==search) { return (middle+1); } else last = middle-1; middle = (first+last)/2; } return 0; }

This is the snapshot of sample output produced after running the above program:

#### Program Explained

- In above program, inside the function
**binarySearchFun()**, if the number gets found or the condition**arr[middle]==search**evaluates to be true, then**middle+1**gets returned to the function**binarySearchFun()**as its return value and this function gets terminated - The return value of this function gets initialized to
**pos**variable inside**main()**function - Otherwise if none of the element (from array) matched to the given number (to be search), then after exiting from the
**while**loop from**binarySearchFun()**function, the**return 0;**statement gets executed and**0**gets returned and initialized to**pos**variable inside the**main() function** - Now use if-else case (in
**main()**function) to check and print whether the number is found or not - If found, then print its position, otherwise print as, number is not found

To learn more about function, refer to Function in C tutorial.

### Binary Search Program in C using Recursion

This is the last program on binary search. This program used recursive function to find the number from the given array using binary search technique. Let's take a look at the program:

#include<stdio.h> #include<conio.h> int binarySearchRecFun(int [], int, int, int); int main() { int i, arr[10], search, pos; printf("Enter 10 elements (in ascending order): "); for(i=0; i<10; i++) scanf("%d", &arr[i]); printf("\nEnter element to be search: "); scanf("%d", &search); pos = binarySearchRecFun(arr, 0, 9, search); if(pos==0) printf("\nThe number, %d is not found in given Array", search); else printf("\nThe number, %d found at Position %d", search, pos); getch(); return 0; } int binarySearchRecFun(int arr[], int first, int last, int search) { int middle; if(first>last) return 0; middle = (first+last)/2; if(arr[middle]==search) return (middle+1); else if(arr[middle]>search) binarySearchRecFun(arr, first, middle-1, search); else if(arr[middle]<search) binarySearchRecFun(arr, middle+1, last, search); }

You will get the same output as shown in the output of above program, that is, binary search using function. To learn more about recursion, refer to Recursion in C tutorial.

#### Same Program in Other Languages

« Previous Program Next Program »

Like/Share Us on Facebook 😋