Binary Search Program in C


#include<stdio.h>
void main()
{
	int i,ar[10],pos=-1, n,mid, lb, ub;
	printf("Enter array in sorted order:-\n");
	for(i=0; i<=9; i++)
	{
		printf("ar[%d]=",i);	
		scanf("%d",&ar[i]);
	}
	lb = 0;
	ub = 9;	
	printf("Enter number to be search=");
	scanf("%d",&n);
	while(lb<ub)
	{
		mid = (lb+ub)/2;
		if(ar[mid]==n)
		{
			pos=mid+1;
			break;
		}
		else if(ar[mid]&lt;n)
		{
			lb = mid+1;
		}
		else
		{
			ub = mid-1;
		}
	}
	if(pos==-1)
	{
		printf("Number not found.");			
	}	
	else
	{
		printf("Position=%d",pos);			
	}
}


Output:

Enter array in sorted order:-
ar[0]=12
ar[1]=24
ar[2]=35
ar[3]=46
ar[4]=49
ar[5]=57
ar[6]=59
ar[7]=61
ar[8]=65
ar[9]=75
Enter number to be search=65
Position=9

c language tutorial, learn c language, study c language,

c language tutorial learn c language