India's Largest Free Online Education Platform

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".
  if(position==-1)
    printf("\n Item not found");
  else
    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;
      count++;
      if(item==arr[mid])
          {
           printf("\n Item found in total no. of steps = %d ",count);
           return mid;
          }
       else if (item<arr[mid])
          high=mid-1;
       else
          low=mid+1;
    }
return -1;
}

Output:

C program for binary search
Output:1
C program for binary search
Output:2

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.

Leave a Reply

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

error: Content is protected !!