Q. 106. Program to accept 'n' numbers into an array and Search for a value using the Linear Search method.
Copy Code:
Learn C++ with more than a hundred solved CPP programs. Get systematic guidance with well designed easy-to-learn progression of lessons that help evolve your understanding of C++ from its simple to advanced concepts and features. Learning C++ helps sharpen your logical skills and this prepares you to write core level program code. C++ professionals contribute extensively in health care, finance, game engines, IOT, embedded systems, machine learning, defense, avionics, aerospace and more.
Q. 106. Program to accept 'n' numbers into an array and Search for a value using the Linear Search method.
Copy Code:
Copy Code:
#include <iostream>
using namespace std;
int main()
{
int a[5], n, i, j, temp, s, low, high, mid;
cout << "How many numbers would you enter ? ";
cin >> n;
cout << "Enter " << n <<" numbers :\n";
for ( i=0 ; i<n ; ++i)
cin >> a[i];
// Sorting Array in Ascending Order for Binary Search
for ( i=0 ; i < n-1 ; ++i )
for ( j = i+1 ; j<n; ++j )
if ( a[ i ] > a[ j ])
{
temp = a[ i ] ;
a[ i ] = a[ j ];
a[ j ] = temp;
}
cout << "\nEnter the number to Search : ";
cin >> s;
low = 0;
high = n-1;
while (low <= high)
{
mid = (low + high)/2 ;
if (s == a[mid])
{
cout << "\nAfter Sorting for Binary Search ";
cout << s << " is PRESENT at Position " << mid +1;
exit (0);
}
else if (s > a[mid])
low = mid + 1;
else
high = mid - 1 ;
}
cout << "\n" << s << " is NOT FOUND";
return 0;
}