1
Program 1
Aim (Write on the ruler page)
Write a program in C++ that first initializes an array of 10 sorted real numbers. The program must verify whether a given element is present in the array or not using the binary search technique. The element to be searched should be entered at the time of execution. If the element is found, the program should display its position in the array; otherwise, it should indicate that the element is not present.
Program (Start from new page after AIM)
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main() {
float a[10], p;
int i, top, bot, mid;
cout << "Type the numbers in ascending order" << endl;
for (i = 0; i < 10; i++) {
cin >> a[i];
}
top = 0;
bot = 9;
cout << "Type the number you want to search: ";
cin >> p;
mid = (top + bot) / 2;
while ((top <= bot) && (a[mid] != p)) {
if (p < a[mid])
bot = mid - 1;
else
top = mid + 1;
mid = (top + bot) / 2;
}
if (a[mid] == p) {
cout << "The number is at position " << (mid + 1) << endl;
} else {
cout << "The number is not found" << endl;
}
getch();
}
Output (Stick on blank page opposite to code)
Download Output