C program for binary search

C program for binary search

#include <stdio.h>
#include <stdlib.h>
int bin_search(int,int,int[]);   // function prototype
int main()   // main function
  int n,item;
  int arr[100];
  printf("\n This is a simple program for binary search \n");

  printf("\n Enter the size of array you want\n");
  scanf("%d",&n); // taking input as length of array

  printf("\n Now Enter the elements of sorted array\n");
  for(int i=0;i<n;i++)
  scanf("%d",&arr[i]); // taking input as sorted array elements

  printf("Array elements entered by you is: ");
  for(int i=0;i<n;i++)
  printf("%d\t",arr[i]);  // printing entered array elements

  printf("\n\n Now enter the element to be searched \n");
  scanf("%d",&item);  // taking input target item 
  int position ;
  position=bin_search(n,item,arr);  // function call (returned value get stored in "position".
    printf("\n Item not found");
    printf("\n Item found at position : %d",position+1);
return 0;
int bin_search(int n,int item,int arr[])  // function definition
  int count=0;
  int low=0;
  int high=n-1;
  while(high>=low)    // while loop
      int mid=(low+high)/2;
           printf("\n Item found in total no. of steps = %d ",count);
           return mid;
       else if (item<arr[mid])
return -1;


C program for binary search
C program for binary search

The above code can’t be directly copy-pasted. You must have to type with your own hand. This is made for your better future. 

Are you made for copy paste?

Absolutely “NO”

Then, try hard to understand this code and type with your own.

About the Author: Make toss

Leave a Reply

Your email address will not be published. Required fields are marked *