Embed presentation
Download to read offline
![/*** program of binary search ****
* http://www.tutorial4us.com/data-structure/c-binary-search */
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int i, first, last, middle, n, search, array[100];
clrscr();
printf("Enter size of array to enter elementsn");
scanf("%d",&n);
printf("Enter %d elementsn", n);
for (i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter element to findn");
scanf("%d", &search);
first = 0;](https://image.slidesharecdn.com/binary-search-150824003622-lva1-app6891/75/Binary-search-1-2048.jpg)
![last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list.n", search);
getch();
}](https://image.slidesharecdn.com/binary-search-150824003622-lva1-app6891/85/Binary-search-2-320.jpg)

This program uses binary search to find a target element in a sorted array. It takes user input for the array size and elements, the target value, and initializes pointers for the first, last, and middle indices. It then repeatedly compares the middle element to the target, updating the pointers for the first or last index accordingly, until the target is found or the search space is exhausted.
![/*** program of binary search ****
* http://www.tutorial4us.com/data-structure/c-binary-search */
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int i, first, last, middle, n, search, array[100];
clrscr();
printf("Enter size of array to enter elementsn");
scanf("%d",&n);
printf("Enter %d elementsn", n);
for (i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter element to findn");
scanf("%d", &search);
first = 0;](https://image.slidesharecdn.com/binary-search-150824003622-lva1-app6891/75/Binary-search-1-2048.jpg)
![last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list.n", search);
getch();
}](https://image.slidesharecdn.com/binary-search-150824003622-lva1-app6891/85/Binary-search-2-320.jpg)