Linear Search in Python and C++

    Here in this program, we will code in Python and C++ to find an element stored in an array using the linear search algorithm. Check it out!

    Linear Search in Python and C++

    In the linear search algorithm, we will transverse through every element of the array and print out the array index number where we find the element:

    C++ Linear Search

    #include<stdio.h>
    #include<conio.h>
    #include<iostream.h>
    
    void main()
    {
    clrscr();
    int n,find,arr[50];
    cout<<"How many elements you want to enter? ";
    cin>>n;
    cout<<"Enter the elements in 1-D array\n";
    
    for(int i=0;i<n;i++)
        cin>>arr[i];
    
    cout<<"Enter the element you want to find: ";
    
    cin>>find;
    
    for(int j=0;j<n;j++)
       { if(arr[j]==find)
         {  cout<<"The element "<<find <<"is at " <<j <<" index";
            break;
           }
       }
    getch();
    }
    

    Output

    How many elements you want to enter? 5
    
    Enter the elements in 1-D array
    
    1
    2
    3
    4
    5
    
    Enter the element you want to find: 3
    
    The element 3 is at 2 index

    Python Linear Search

    arr=[]
    n= int(input("How many elements you want to enter? "))
    print("Enter the elements in 1-D array")
    for i in range(n):
        elements = int(input())
        arr.append(elements)
    find= int(input("Enter the element you want to find: "))
    for i in range(n):
        if arr[i]==find:
            print("The element",find, "is at",i,"index")
            break

    Output

    How many elements you want to enter? 6
    
    Enter the elements in 1-D array
    
    12
    42
    12
    34
    576
    3
    
    Enter the element you want to find: 576
    The element 576 is at 4 index

    Conclusion

    Try out these two codes mentioned above and practice the linear search. It has many real-life implications, such as phone books, searching documents, emails and messages, finding files on a computer, and more. Although linear search is not the most efficient, it is the most preferable in the case of small datasets.

    We hope that the above tutorial helps you sort your coding issues while performing linear search using Python and C++.

    Happy coding!

    People are also reading: