- 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 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 Program for Binary Search
In this article, you'll learn and get code about how to search for an element in a given array using the binary search technique. But before going through the program, if you are not aware of how binary search works, then I recommend that you go through the step-by-step workings of binary search..
The following is a list of the programs you will go through, along with a step-by-step explanation:
- binary search program without using a user-defined function
- binary search program using a user-defined function
- binary search program using recursion
Binary Search in C
This is the simplest program for a binary search. In the most basic sense, we have asked the user to enter 10 elements or numbers without specifying the size of the array and then enter the required number of elements. Also, the sorting code block is not included in this program. So I've just asked to enter an 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 in the Code::Blocks IDE. Here is the initial snapshot of the 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 the ENTER key. Again, enter any element or number to be searched, say 7, and press the ENTER key to see the output given in the snapshot here:
If the user supplies all 10 numbers as entered in the above output, However, when he/she entered any number, say 15, to be searched from the given list of numbers, the following is the output:
Program Explained
- Declare all the required variables, say i, arr[], search, first, last, and middle of int (integer) type.
- The size of arr[] is declared to be 10 in order to store up to ten elements, or numbers.
- Now receive 10 numbers as input from the user.
- As indexing in an array starts at 0, the first element gets stored in arr[0], the second element gets stored in arr[1], and so on.
- Now, enter the number to be searched and save it in the search variable.
- Now initialize 0 to the first (index), 9 to the last (index), and find the value of the middle (index) using first+last/2.
- Create a while loop that continues running until the value of first (index) becomes less than or equal to the value of last (index).
- The meaning of the above step is that the process inside the loop continues running until the interval becomes zero, as told in the logic given at the start of this article.
- Inside the while loop, first check whether the value at the middle index (arr[middle]) is less than search (the number to be searched) or not using an 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 the 9th step returns a false result, proceed to the next steps.
- The program flow now moves to the else-if section, which checks whether the element in the middle (arr[middle]) is equal to the search (the number to be searched) or not.
- If it is equal, then print the position. Here we have increased the index number by one to display the position of the number. As indexing starts at 0. For example, in an array, there are 4 numbers, say 10, 20, 30, and 40. As a result, the index will be 0, 1, 2, and 3. But normally people know it like this: 10, 20, 30, and 40 are present at first, second, third, and fourth positions.
- So i have added 1 to the middle and printed its value as the position of the given number in the array.
- Now the program flow goes to the last statement of the while loop, which is middle = (first+last)/2;.
- If the 12th step evaluates to false, the else block is evaluated, and middle-1 is assigned to last, and the loop is repeated until the condition of the while loop evaluates to false.
Here is the modified version of the binary search program (as given above) in C. We've left the size of the array to the user to decide at runtime. 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 a number from a sorted array, not from the actual array that is entered by the user at run-time. For example, if the user supplies 10, 50, 20, 30, and 40 as array elements, and 20 as the number to search, Then this program sorts the array, so the array becomes 10, 20, 30, 40, and 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 a snapshot of the sample run:
Binary search program in C using user-defined functions
Modify the first program in this article that does the same job, but this time using the 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 a snapshot of the sample output produced after running the above program:
Program Explained
- In the 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 the pos variable inside the main() function.
- Otherwise, if none of the elements (from the array) matched the given number (to be searched), then after exiting from the
while loop from the binarySearchFun() function, the
return 0;
statement gets executed, and 0 gets returned and initialized to the pos variable inside the main() function. - Now use the if-else case (in the 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."
Binary Search Program in C using Recursion
This is the last program on binary search. This program used a recursive function to find the number from the given array using the 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 the above program, that is, a binary search using the function.
The same program in different languages
« Previous Program Next Program »