HSC – Binary Search in C++ | EXP – 2

write a program in C++ that first initialize an array of given 10 sorted real numbers. The program must verify whether the given element is to an array or not, using a binary search technique. The element is to be entered at the time of execution. If the number is found, the program should print its position in the array otherwise it should print the number that is not found.

#include<iostream.h> // header file for input/output operations
#include<conio.h> // header file for console input/output operations
#include<stdlib.h> // header file for standard library functions

void main()
{
	float a[10], p; // declaring an array 'a' of size 10 and a variable 'p' of type float
	int i, top, bot, mid; // declaring integer variables 'i', 'top', 'bot', and 'mid'
	cout << "Type the number in ascending order" << "\n"; // prompt the user to enter 10 floating-point numbers in ascending order
	for (i = 0;i < 10;i++) { cin >> a[i]; } // read the 10 floating-point numbers into the array 'a'
	top = 0; bot = 9; // set the top and bottom bounds for the binary search algorithm
	cout << "Type the number you want to search \n"; // prompt the user to enter the number they want to search for
	cin >> p; // read the number to search for into variable 'p'
	mid = (top + bot) / 2; // calculate the middle index of the array 'a'
	while ((top <= bot) && (a[mid] != p)) // execute the loop until either the number is found or the entire array has been searched
	{
		if (p < a[mid]) // if the number is less than the middle value
			bot = mid - 1; // update the bottom bound to exclude the upper half of the array
		else // if the number is greater than or equal to the middle value
			top = mid + 1; // update the top bound to exclude the lower half of the array
		mid = (top + bot) / 2; // calculate the new middle index of the array 'a'
	}
	if (a[mid] == p) // if the number is found in the array
	{
		cout << "the number is at position" << (mid + 1) << "\n"; // output the position of the number
	}
	else // if the number is not found in the array
		cout << "The number is not found\n"; // output a message indicating that the number was not found
	getch(); // wait for a character to be entered before terminating the program
}

Leave a Comment

Scroll to Top