C Program Binary Search in Array

By | March 8, 2020

C Program Binary Search in Array

#include <stdio.h>
int main()
{
  int i, first, last, middle, n, item, a[100];

  printf("Enter number of elements in array[Maximum 100] = ");
  scanf("%d", &n);

  printf("Please, Enter %d elements in Ascending order in this array\n ", n);

  for (i = 0; i < n; i++)
    {
	printf("Enter Element number %d in array = ", i+1);
	scanf("%d", &a[i]);
	}

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

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

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

    middle = (first + last)/2;
  }
  if (first > last)
    printf("%d Not found in this array", item);

  return 0;
}

Output 1

Enter number of elements in array[Maximum 100] = 5
Please, Enter 5 elements in Ascending order in this array
Enter Element number 1 in array = 123
Enter Element number 2 in array = 145
Enter Element number 3 in array = 200
Enter Element number 4 in array = 245
Enter Element number 5 in array = 350
Enter value to search = 200
200 found at location 3 in this array.

Output 2

Enter number of elements in array[Maximum 100] = 10
Please, Enter 10 elements in Ascending order in this array
Enter Element number 1 in array = 12
Enter Element number 2 in array = 13
Enter Element number 3 in array = 14
Enter Element number 4 in array = 15
Enter Element number 5 in array = 16
Enter Element number 6 in array = 70
Enter Element number 7 in array = 80
Enter Element number 8 in array = 90
Enter Element number 9 in array = 100
Enter Element number 10 in array = 125
Enter value to search = 500
500 Not found in this array

 956 total views,  1 views today

Leave a Reply

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