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.
- #include "stdafx.h"
- #include < iostream >
- #include < conio.h >
- using namespace std;
- int main() {
- int a[5], n, i, se;
- cout << "Enter the number of elements to be inserted:" << endl;
- cin >> n;
- cout << "Enter " << n << " elements:\n";
- for (i = 0; i < n; i++) {
- cin >> a[i];
- }
- cout << "Elements are:\n";
- for (i = 0; i < n; i++) {
- cout << a[i] << "\t";
- }
- cout << "\n";
- cout << "Enter searching elements:\n";
- cin >> se;
- for (i = 0; i < n; i++) {
- if (a[i] == se) {
- cout << se << " element found at " << i + 1 << " location\n";
- break;
- }
- }
- if (i == n) {
- cout << "Element not found\n";
- }
- system("pause");
- }
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.