C Program to search a key element using Binary Search method

Program

#include<stdio.h>
void main()
{
	int n, i, key, low, mid, high, a[10], flag;
	flag = 0;
	printf("Enter the size of the array\n");
	scanf("%d", &n);
	printf("Enter %d numbers in ascending order\n", n);
	for(i = 0; i < n; i++)
	{
		scanf("%d", &a[i]);
	}
	printf("Enter the key element to be searched\n");
	scanf("%d", &key);
	low = 0;
	high = n - 1;
	while(low <= high)
	{
		mid = (low + high) / 2;
		if(key > a[mid])
		{
			low = mid + 1;
		}
		else if(key < a[mid])
		{
			high = mid - 1;
		}
		else if(a[mid] == key)
		{
			flag = 1;
			break;
		}
	}
	if(flag == 1)
		printf("Key element found at position %d\n", mid + 1);
	else
		printf("Key element not found\n");
}

Output 1

Enter the size of the array
5
Enter 5 numbers in ascending order
13
37
42
78
91
Enter the key element to be searched
91
Key element found at position 5

Output 2

Enter the size of the array
6
Enter 6 numbers in ascending order
11
32
63
78
82
88
Enter the key element to be searched
11
Key element found at position 1

Output 3

Enter the size of the array
5
Enter 5 numbers in ascending order
10
11
23
40
81
Enter the key element to be searched
12
Key element not found