0% found this document useful (0 votes)
14 views2 pages

Binary Search Implementation in C

The document presents a C program that implements binary search on an array of integers. It searches for a target value (7) in a predefined sorted array and outputs the index if found. In this case, the target is found at index 3.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views2 pages

Binary Search Implementation in C

The document presents a C program that implements binary search on an array of integers. It searches for a target value (7) in a predefined sorted array and outputs the index if found. In this case, the target is found at index 3.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LAB PROGRAM-5

Implement Binary Search on Integers.

#include <stdio.h>

int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 7;

int left = 0;
int right = size - 1;
int found = 0; // Flag to indicate if the target is found
int mid;

while (left <= right) {


mid = left + (right - left) / 2;

if (arr[mid] == target) {
printf("Element found at index %d\n", mid);
found = 1;
break;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

if (!found) {
printf("Element not found\n");
}

return 0;
}

OUTPUT—
Element found at index 3

You might also like