Program for binary search in C

#include <stdio.h>

int main()
{
   int c, first, last, middle, n, search, array[100];

   printf("Enter number of elementsn");
   scanf("%d",&n);

   printf("Enter %d integersn", n);

   for ( c = 0 ; c < n ; c++ )
      scanf("%d",&array[c]);

   printf("Enter value to findn");
   scanf("%d",&search);

   first = 0;
   last = n - 1;
   middle = (first+last)/2;

   while( first <= last )
   {
      if ( array[middle] < search )
         first = middle + 1;
      else if ( array[middle] == search )
      {
         printf("%d found at location %d.n", search, middle+1);
         break;
      }
      else
         last = middle - 1;

      middle = (first + last)/2;
   }
   if ( first > last )
      printf("Not found! %d is not present in the list.n", search);

   return 0;
}

Output
Enter number of elements
9
Enter 9 integers
9
8
5
6
4
7
3
1
11
Enter value to find
9
9 found at location 1.




Discover more from PlusDigit

Subscribe to get the latest posts sent to your email.

Discover more from PlusDigit

Subscribe now to keep reading and get access to the full archive.

Continue reading

AdBlock Detected!

Please disable your AdBlocker to access this website.

Once disabled, this message will disappear automatically.