Write a C program to accept n elements from users and store it in an array. Accept a value from the user and use binary search method to check whether the value is present in the array or not. Display proper message. (Students should accept sorted arrays and use a Recursive function).
#include <stdio.h>
#define MAX 100
// Recursive Binary Search Function
int binarySearch(int arr[], int low, int high, int key) {
if (low > high)
return -1; // Not found
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
else if (key < arr[mid])
return binarySearch(arr, low, mid - 1, key);
else
return binarySearch(arr, mid + 1, high, key);
}
int main() {
int arr[MAX], n, key, result;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d sorted elements (ascending order):\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter value to search: ");
scanf("%d", &key);
result = binarySearch(arr, 0, n - 1, key);
if (result != -1)
printf("Element %d found at position %d.\n", key, result + 1);
else
printf("Element %d not found in the array.\n", key);
return 0;
}
