C++ Program Linear Search in Array

Here is 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

#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

Recommended Posts
C++ Program to Find Average of Numbers Using Arrays
C++ Program to Find Largest Element of an Array
C++ Program to Find Smallest Element in Array
C++ Program to Delete Spaces from String or Sentence
C++ Program to Delete Vowels Characters from String
C++ Program to Find the Frequency of Characters in a String
C++ Program to find length of string
C++ Program to Add Two Distances in Inch and Feet
C++ Program to Check for Armstrong Number
C++ Program to Find Transpose of a Matrix
C++ Program to Delete a Word from Sentence
All C++ Programs