Write a program that initializes data into one-dimensional array. The data must be in ascending order. It inputs a value from the user and searches this value in the array using binary search method.
So let’s Write Code:
Code:
Write a program that initializes data into one-dimensional array. Search value using binary search.
#include"iostream"
using namespace std;
main()
{
int abc[10] = {1,3,9,15,78,87,95,103,124,352};
int loc, num, i, M, S = 0, E = 9;
loc = 0;
cout<<"Enter any value ? ";
cin>>num;
while(S<=E)
{
M = (S + E)/2;
if(num == abc[M])
{
loc = M+1;
break;
}
else if(num < abc[M])
E = M - 1;
else
S = M + 1;
}
if(loc == 0)
cout<<"Value not found "<<endl;
else
cout<<"Value found at position = "<<loc<<endl;
}
Hope You will learn Something. Happy Coding.
Visit my YouTube Channel as Well๐ https://www.youtube.com/watch?v=JuIHQ9cLSEw&list=PLbIhkHxfUIItTdcyCb34uRIrPJbXBndIl&index=4
Click on the below Links for more Programming Exercises:
Conditional Structure Exercises: ๐https://myustaadg.com/category/programming-exercises/conditional-structures-exercises/
Array Exercises: ๐https://myustaadg.com/category/programming-exercises/arrays-exercises/