Articles

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.

#include<iostream>
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)
        cout<<i<<"\t";
        t = true;
    }
    if(t==false){
        cout<<"Element not found\n";
    }
}

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

OUTPUT :

Enter the number of elements

7
Enter the elements of the array
12 34 13 65 23 10 15
Enter the element to be searched
10
The position of element: 10 is/are in index 5
 
EXPLANATION :
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

WORKING :

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:

O(n)

 

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 tutorialsinhand.com

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 https://www.linkedin.com/in/sayantan-bose-14134a1a6/ - šŸ˜„ 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!