Linear Search in Python and C++

By | August 5, 2019

Here in the program, we will code to find an element stored in an array, using the linear search algorithm.

Linear Search in Python and C++

In 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++:

#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

Leave a Reply

Your email address will not be published. Required fields are marked *