From 881d4fb8c1bdc90847da636ad0f9d32b167020f7 Mon Sep 17 00:00:00 2001 From: Ganesh Karthik R Date: Tue, 10 Oct 2023 18:38:45 +0530 Subject: [PATCH] Basic program II --- C/Array/b_search.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C/Array/b_search.c diff --git a/C/Array/b_search.c b/C/Array/b_search.c new file mode 100644 index 0000000..58a06ca --- /dev/null +++ b/C/Array/b_search.c @@ -0,0 +1,44 @@ +#include + +int main() { + int size; + printf("Enter the size of the array: "); + scanf("%d", &size); + + int arr[size]; + + printf("Enter %d sorted elements:\n", size); + for (int i = 0; i < size; i++) { + scanf("%d", &arr[i]); + } + + int target; + printf("Enter the number you want to search for: "); + scanf("%d", &target); + + int left = 0; + int right = size - 1; + int found = 0; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (arr[mid] == target) { + printf("Element %d found at index %d\n", target, mid); + found = 1; + break; + } + + if (arr[mid] < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + if (!found) { + printf("Element %d not found in the array\n", target); + } + + return 0; +}