w3resource logo

:

C Programming Exercises

C Exercises: Binary search

C Programming Searching and Sorting Algorithm: Exercise-1 with Solution

Write a C program for binary search.
Note: Binary Search : In computer science, a binary search or half-interval search algorithm finds the position of a target value within a sorted array. The binary search algorithm can be classified as a dichotomies divide-and-conquer search algorithm and executes in logarithmic time.
Given a sorted array arra[] of n elements, write a function to search a given element x in arra[].

Pictorial presentation - Binary search algorithm :

C programming Binary search algorithm : part-1

C programming Binary search algorithm : part-2

C programming Binary search algorithm : part-3

Sample Solution :

C Code :

#include<stdio.h>
  void main()
  {
  int  arra[100],i,n,x,f,l,m,flag=0;
  printf("Input no. of elements in  an array\n");
  scanf("%d",&n);
  printf("Input  %d value in ascending order\n",n);
  for(i=0;i<n;i++)
  scanf("%d",&arra[i]);
  printf("Input  the value to be search : ");
  scanf("%d",&x);
  /* Binary Search  logic */
  f=0;l=n-1;
  while(f<=l)
  {
  m=(f+l)/2;
  if(x==arra[m])
  {
  flag=1;
  break;
  }
  else  if(x<arra[m])
  l=m-1;
  else
  f=m+1;
  }
  if(flag==0)
  printf("%d  value not found\n",x);
  else
  printf("%d value  found at %d position\n",x,m);
  }

Sample Output:

Input  no. of elements in an array                                                                            
3                                                                                                             
Input  3 value in ascending order                                                                             
15                                                                                                            
18                                                                                                            
20                                                                                                            
Input  the value to be search : 15                                                                            
15 value  found at 0 position

Flowchart:

Flowchart: C Programming - Binary search

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.