0
1.6kviews
Write a Python program to perform Linear Search / Linear Search in Python
1 Answer
0
47views

Explanation:-

  • Create a variable n which stores the no of elements user wants to add to the list.
  • Iterate for loop n times and take the elements entered from the user and append them to a list a.
  • Initialize 2 variable flag and index to 0 where flag represents the status and index the position the element in the list.
  • Take a input the from the user the element to be searched.
  • Iterate over the the list to check if the element is present the list the if present then copy the value of the index of to the variable to index & assign 1 to the flag variable.
  • At the end check the status of the flag variable if its 1 then the print element found & the index of the element, If not found then print element not found.

Code:-

a=[]
n=int(input("Enter no elements:- "))
flag=index=0
for i in range(n):
    print("Enter elements:- ",i)
    a.append(int(input()))
print(a)    
x=int(input("enter the no to be searched search "))
for i in range(n):
    if (x==a[i]):
        index=i
        flag=1
        break


if(flag==0):
    print("Element Not Found")
else:
    print("Element Found at index",index)

Output:-

enter image description here

enter image description here

Please log in to add an answer.