Linear Search Using C++

Searching and sorting are the two methods for retrieving data more efficiently.There are different types of methods available for searching and sorting. In this blog we will discuss the Linear Search method.

First, the data must be stored in an array. Then, in linear search method, the required data will be searched in a sequential manner. If the required data is available, then it will search the location and find where the data is available and exists. Otherwise, it will search the entire array from the beginning to the ending position and display that the searching element is not found.

First, open your favorite IDE for C++ and then, write the following code.

 
  1. #include "stdafx.h"  
  2. #include < iostream >   
  3. #include < conio.h >  
  4. using namespace std;  
  5. int main() {  
  6.     int a[5], n, i, se;  
  7.     cout << "Enter the number of elements to be inserted:" << endl;  
  8.     cin >> n;  
  9.     cout << "Enter " << n << " elements:\n";  
  10.     for (i = 0; i < n; i++) {  
  11.         cin >> a[i];  
  12.     }  
  13.     cout << "Elements are:\n";  
  14.     for (i = 0; i < n; i++) {  
  15.         cout << a[i] << "\t";  
  16.     }  
  17.     cout << "\n";  
  18.     cout << "Enter searching elements:\n";  
  19.     cin >> se;  
  20.     for (i = 0; i < n; i++) {  
  21.         if (a[i] == se) {  
  22.             cout << se << " element found at " << i + 1 << " location\n";  
  23.             break;  
  24.         }  
  25.     }  
  26.     if (i == n) {  
  27.         cout << "Element not found\n";  
  28.     }  
  29.     system("pause");  
  30. }  
 
 

Output

 
 

Conclusion

Now, we have created a program for linear search. 

NOTE

The following code may differ slightly for different IDEs like Turbo C or C++, CodeBlocks. 
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now