C++ Program Linear Search in Array

  • Write a C++ program to search an element in an array using linear search.

In this C++ program we have to search an element in a given array using linear search algorithm. If given element is present in array then we will print it's index otherwise print a message saying element not found in array.

For Example :
Input Array : [2, 8, 4, 2, 14, 10, 15]
Element to search : 4

Output : 
Element found at index 2 
Algorithm to search an element in array using linear search
  • First take number of elements in array as input from user and store it in a variable N.
  • Using a loop, take N numbers as input from user and store it in array(Let the name of the array be inputArray).
  • Ask user to enter element to be searched. Let it be num.
  • Now, using a for loop, traverse inputArray from index 0 to N-1 and compare num with every array element. If num is equal to any array element then print a message saying "Element found at index 4" otherwise print "Element Not Present".

C++ program for linear search in array

// C++ Program to search any element or number in an array

#include <iostream>
using namespace std;
  
int main(){
    int input[100], count, i, num;
      
    cout << "Enter Number of Elements in Array\n";
    cin >> count;
    
    cout << "Enter " << count << " numbers \n";
     
    // Read array elements
    for(i = 0; i < count; i++){
        cin >> input[i];
    }
     
    cout << "Enter a number to serach in Array\n";
    cin >> num;
     
    // search num in inputArray from index 0 to elementCount-1 
    for(i = 0; i < count; i++){
        if(input[i] == num){
            cout << "Element found at index " << i;
            break;
        }
    }
     
    if(i == count){
        cout  << "Element Not Present in Input Array\n";
    }

    return 0;
}
Output
Enter Number of Elements in Array
6
Enter 6 numbers
8 4 7 1 3 9
Enter a number to serach in Array
3
Element found at index 4
Enter Number of Elements in Array
6
Enter 6 numbers
8 4 7 1 3 9
Enter a number to serach in Array
2
Element Not Present in Input Array