C++ Program For Linear Search in an Array.

 The following Program will perform a linear search in an array to find an element.

Linear Search Image Representation.

C++ Program for Linear Search in Array:

Let's understand the concept of linear Search first. In linear Search, We check every element of the array and compare it with our required element. If any entry matches the required element, the Search is stopped and the index number is printed out.

Source Code:

#include <iostream>

using namespace std;

int main()
{
    int sizeOfArray = 10;
    int arr[sizeOfArray];
    for (int i = 0i < sizeOfArrayi++)
    {
        arr[i] = i+1;
    }
    
    cout << "Enter element which you want to search: ";
    int item;
    cin >> item;
    bool itemFound = false;

    for (int i = 0i < sizeOfArrayi++)
    {
        if (arr[i] == item)
        {
            cout << item << " is present at index number " << i << " in the array." << endl;
            itemFound = true;
            break;
        }
    }
    if (itemFound == false)
    {
        cout << item << " is not found in the array." << endl;
    }
    
    // printing original array:
    cout << "Original Array:" << endl;
    for (int i = 0i < sizeOfArrayi++)
    {
        cout << arr[i<< " ";
    }
    cout << endl;
    

    return 0;
}

Output:

Enter element which you want to search: 5
5 is present at index number 4 in the array.
Original Array:
1 2 3 4 5 6 7 8 9 10 

Alternate Output:

Enter element which you want to search: 15
15 is not found in the array.
Original Array:
1 2 3 4 5 6 7 8 9 10 

Keypoint:

  • Linear Search is the most basic search technique used to find an element in the array.
  • Linear Search can also be performed in an unsorted array.

If you have any queries about this program or about anything, do ask in a comment. I will try to answer as many questions as I can.

Comments