Linear Search in C++


Q.Write a C++ program for Linear Search.

#include <iostream>       
using namespace std;
  
int main()
{  
    int a[25], search, size, i;
    cout << "Enter number of elements in array: ";
    cin >> size;
    cout << "Enter the integers: ";
    for (i = 0; i < size; i++)
    {
        cin >> a[i];
    }
    cout << "Enter the number to search: ";
    cin >> search;
    for (i = 0; i < size; i++)
    {
        if (a[i] == search)  
        {
            cout << search << " is present in the array.";
            break;
        }
    }
    if (i == size)
    {
    	cout << search << " is n't present in the array.";
    }
   return 0;    
}

Q. Write an algorithm to Linear Search using C++.

1. Start
2. Prompt the user to enter the number of elements (`size`) in the array.
3. Read the value of `size`.
4. Declare an integer array `a` of size at least `size`.
5. Prompt the user to enter the elements of the array.
6. For each index `i` from 0 to `size - 1`:
     - Read the integer and store it in `a[i]`.
7. Prompt the user to enter the element to search (`search`).
8. Read the value of `search`.
9. Initialize a variable `i` to 0.
10. Loop `i` from 0 to `size - 1`:
    - If `a[i]` is equal to `search`:
    - Print "`search` is present in the array."
    - Exit the loop.
11. After the loop, if `i` reached `size` (loop completed without finding the element):
    - Print "`search` isn't present in the array."
12. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.