C Program for binary search

Binary search is one the searching algorithms to search for an element in an array. This C program for binary search will clear your concept about binary search algorithm.

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a[50],elem,mid,high,low,n,i;
printf("enter number of elements to enter");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("enter %d element",i+1);
scanf("%d",&a[i]);

}
printf("enter element to search");
scanf("%d",&elem);
low=0;
high=n-1;
while(low<=high){
mid=(low+high)/2;
if(a[mid]==elem){
printf("Element Found at index %d",mid);
break;
}
else if(a[mid]>elem){
high=mid-1;
}

else if(elem>a[mid])
low=mid+1;
else {
printf("element not found");
break;

}

}
return 0;
}

 

Output