Get Website Learn Coding Tech Story

C Programming Examples

#include<stdio.h>

int main() {

	/* For binary search, the array should be arranged in ascending or descending order */
	int data[] = {1,2,3,4,5,6,7,8,9,10};

	/* 'min' use for starting location of the array, 'max' use for end location of the array and 'mid' use for middle location of the array */
	int min = 0, max = 10, search, mid = (max + min) / 2;
	printf("Enter a number to search:\n");
	scanf("%d", &search);
	while(min <= max) {
		if(data[mid] < search)
			min = mid + 1;
		else if(data[mid] ==  search) {
			printf("%d is found at location %d!\n", search, mid+1);

			/* If data found in the list then 'while' loop terminate */
			break;
		}
		else
			max = max - 1;
		mid = (max + min) / 2;
	}
	if(min > max)
		printf("%d is not found!\n",search);
	return 0;
}


          /****** Output ******/
          

Enter a number to search:


4


4 is found at location 4!




----------------------------------




Enter a number to search:


13


13 is not found!

Learn more about Binary Search