//Program 8: Develop C program to search for a key element in an array of ‘n’
elements using binary seach.
#include <stdio.h>
int main()
{
int n, key, low, high, mid, i;
// Input the number of elements in the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int array[n];
// Input the elements of the array
printf("Enter %d elements in sorted order:\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
// Input the key to search
printf("Enter the key to search: ");
scanf("%d", &key);
// Initialize low and high indices
low = 0;
high = n - 1;
// Perform binary search
while (low <= high)
{
mid = (low + high) / 2;
if (array[mid] == key)
{
printf("Key %d found at position %d.\n", key, mid + 1);
return 0;
}
else if (array[mid] < key)
{
low = mid + 1; // Search in the right half
}
else
{
high = mid - 1; // Search in the left half
}
}
// If the loop completes without finding the key
printf("Key %d not found in the array.\n", key);
return 0;
}