- C Programming Examples
- C Programming Examples
- C Print Hello World
- C Get Input from User
- C Print Integer
- C Add Two Numbers
- 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 Check Reverse equal Original
- C Add Subtract Multiply Divide
- C Make Calculator
- C Add Digits of Number
- C Calculate Average, Percentage
- C Calculate Arithmetic Mean
- C Calculate Student Grade
- C Print Table of Number
- C Print Prime Numbers
- C Add n Numbers
- C Interchange Numbers
- C Reverse a Number
- C Swap Two Numbers
- C Count Positive Negative Zero
- C Find Largest of Two Numbers
- C Find Largest 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 Area & Perimeter of Square
- C Area & Perimeter of Rectangle
- C Area & Circumference of Circle
- C Convert Fahrenheit to Celsius
- C Convert Celsius to Fahrenheit
- C Print ASCII Value
- C Print Fibonacci Series
- C Check Palindrome or Not
- C Check Armstrong or Not
- C Generate Armstrong Numbers
- C Find nCr and nPr
- C Convert Decimal to Binary
- C Convert Decimal to Octal
- C Convert Decimal to Hexadecimal
- C Convert Binary to Decimal
- C Convert Binary to Octal
- C Convert Binary to Hexadecimal
- C Convert Octal to Decimal
- C Convert Octal to Binary
- C Convert Octal to Hexadecimal
- C Convert Hexadecimal to Decimal
- C Convert Hexadecimal to Binary
- C Convert Hexadecimal to Octal
- C Pattern Printing Programs
- C Print Diamond Pattern
- C Print Floyd's Triangle
- C Print Pascal's Triangle
- C Print Smiling face
- C 1D Array Programs
- C Linear Search
- C Binary Search
- C Add Two Numbers using Pointer
- C Find Largest Element in Array
- C Find Smallest Element in Array
- 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 2D Array Programs
- C Add Two Matrices
- C Subtract Two Matrices
- C Transpose a Matrix
- C Multiply Two Matrices
- C 3D Array 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 Delete Vowels from String
- C Delete Word from String
- C Find Frequency of Character
- C Count Word in String
- C Remove Spaces from String
- C Sort a String
- C Uppercase to Lowercase
- C Lowercase to Uppercase
- C Swap Two Strings
- C Check Anagram or Not
- C Generate Random Numbers
- C Read a File
- C Write Content to File
- C Read & Display File
- C Copy a File
- C Merge Two Files
- C List Files in Directory
- C Delete a File
- C Encrypt & Decrypt a File
- C Print Date
- C Get IP Address
- C Shutdown Computer
- C More Programs
- C Check Palindrome String
- C Inches to Centimetres
- C Kilogram to Gram
- C Count Even Odd
- C Count Vowels Consonants
- C Find Profit Loss
- C Sum All Matrix Elements
- C First & Last Digit Sum
- C Largest Element in Matrix
- C Pass Array to Function
- C Address of Variable
- C Array Element at Even
- C Array Element at Odd
- C Print Even Array Elements
- C Print Odd Array Elements
- C Reverse File
- C Print Message with Time
- C Print Number in Words
- C Print Successive Character
- C Sum of their Square
- C Replace Vowel in String
- C Sort Words in Ascending
- C Sort Words in Descending
- C Sort String in Alphabetical
- C Programming Tutorial
- C Tutorial
- C Programming Library
- C Standard Library
- C Programming Test
- C Programming Test
- Give Online Test
- All Test List

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

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:

// Binary Search in C // ----codescracker.com------ #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:

- 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**.

// Complete Version of Biinary Search Program in C // ----codescracker.com------ #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:

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:

// Binary Search Program in C using Function // ----codescracker.com------ #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:

- 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.

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:

// Binary Search Program in C using Recursion // ----codescracker.com------ #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.