C++ program to search an element using linear search in array

C++ program to search an element using linear search in array

In this chapter of C++ program tutorial out task is: 

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

C++ program to search an element using linear search

Below is the C++ program to search an element using linear search.

using namespace std;
void linearSearch(int arr[], int n, int x)
    bool t = false;
    cout<<"The position of element: "<<x<<" is/are in index ";
    for(int i=0;i<n;i++){
        if (arr[i] == x)
        t = true;
        cout<<"Element not found\n";

int main()
    int n,i,x;
    cout<<"Enter the number of elements\n";
    int arr[n];
    cout<<"Enter the elements of the array\n";
    cout<<"Enter the element to be searched\n";
    linearSearch(arr, n, x);
    return 0;


Enter the number of elements

Enter the elements of the array
12 34 13 65 23 10 15
Enter the element to be searched
The position of element: 10 is/are in index 5
In the above program:
  • By calling the function linearSearch the array , number of element and the the element to searched are passed
  • Then in the function the iteration starts from 0 th element and it searches the element from passing one by one index
  • When the element to be searched matches with the array element then the index is displayed.

image of linear search


arr[] = {12 , 34, 13, 65, 23, 10, 15}

n = 7

x = 10

1st iteration

if(arr[i] == x)    //  12 == 10   -> false

2nd iteration

if(arr[i] == x)    //  34 == 10   -> false

3rd iteration

if(arr[i] == x)    //  13 == 10   -> false

4th iteration

if(arr[i] == x)    //  65 == 10   -> false

5th iteration

if(arr[i] == x)    //  23 == 10   -> false

6th iteration

if(arr[i] == x)    //  10 == 10   -> true [index 5 returned]

7th iteration

if(arr[i] == x)    //  15 == 10   -> false

The loop ends with this.


Time complexity:



You can see the above code execution and output in codeblocks IDE:

C++ program to search an element by linear search


CPP Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by

About the Author
Sayantan Bose
- šŸ”­ Iā€™m currently working on DS Algo skills - šŸŒ± Iā€™m currently learning web develeopement - šŸ‘Æ Iā€™m looking to collaborate with Oppia - šŸ“« Reach me at - šŸ˜„ Pronouns: his/him
Page Views :    Published Date : Aug 31,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!