C Program Binary Search

« Previous Program Next Program »

Binary Search in C

To perform binary search in C programming, you have to ask to the user to enter the array size then ask to enter the array elements. Now ask to enter an element to be search, to start searching that element using binary search technique

C Programming Code for Binary Search

Following C program first ask to the user to enter "how many element he/she want to store in the array", then ask to enter the array element one by one". After storing the element in the array, program ask to enter the element which he/she want to search in the array whether the number/element is present or not in the given array. The searching technique used here is binary search which is fast technique:

/* C Program - Binary Search */
void main()
	int n, i, arr[50], search, first, last, middle;
	printf("Enter total number of elements :");
	printf("Enter %d number :", n);
	for (i=0; i<n; i++)
	printf("Enter a number to find :");
	scanf("%d", &search);
	first = 0;
	last = n-1;
	middle = (first+last)/2;
	while (first <= last)
		if(arr[middle] < search)
			first = middle + 1;

		else if(arr[middle] == search)
			printf("%d found at location %d\n", search, middle+1);
			 last = middle - 1;
		middle = (first + last)/2;
	if(first > last)
		printf("Not found! %d is not present in the list.",search);

When the above c program is compile and executed, it will produce the following result. Above C Programming Example Output (Element found):

binary search c

Above C Programming Example Output (Element Not found):

c binary search program

Same Program in Other Programming Language

You may also like same program in other programming languages:

« Previous Program Next Program »


Quick Links
Signup - Login - Give Online Test