C++ Program to Perform Linear Search on a List of Numbers

1. Introduction

Linear search is a simple way to find a specific number in a list. It starts at the beginning of the list and checks each number one by one. If it finds the number you're looking for, it stops. Otherwise, it keeps going until it reaches the end of the list. In this blog post, we'll show you how to do this with a C++ program.

2. Program Overview

1. Define and initialize the array or list.

2. Accept the number to be searched.

3. Scan each element of the list.

4. If the element matches with the searched number, display its position.

5. If the end of the list is reached, indicate that the number is not present.

3. Code Program

#include <iostream>
using namespace std;

int main() {
    int n, num, i, flag = 0;

    // Input number of elements
    cout << "Enter the number of elements in the array: ";
    cin >> n;
    int arr[n];

    // Input array elements
    cout << "Enter the elements of the array:" << endl;
    for(i = 0; i < n; i++) {
        cin >> arr[i];
    }

    // Number to be searched
    cout << "Enter the number to be searched: ";
    cin >> num;

    // Linear Search
    for(i = 0; i < n; i++) {
        if(arr[i] == num) {
            flag = 1;
            break;
        }
    }

    if(flag == 1) {
        cout << "Number " << num << " is present at position " << i+1 << endl;
    } else {
        cout << "Number " << num << " is not present in the array." << endl;
    }

    return 0;
}

Output:

Enter the number of elements in the array: 5
Enter the elements of the array:
14 25 36 32 26
Enter the number to be searched: 32
Number 32 is present at position 4

4. Step By Step Explanation

1. Array Initialization: We capture the size of the array and its elements from the user.

2. Number to be Searched: We also capture the number that needs to be searched within the list.

3. Linear Search: We then go through each element of the list one by one. If the element matches with the number we are searching for, we set a flag and break out of the loop.

4. Result: Depending on the flag value, we either display the position where the number is found or mention that the number is not present in the list.

Linear search is straightforward but not the most efficient searching algorithm, especially for large lists. However, it serves as a fundamental introduction to searching techniques in computer science.

Comments