Task:
Write a program which will take an input from the user and search it in a built in
array using the linear search algorithm.
For Example:
BuiltInArray = [Apple, Orange, Grape, Strawberry, Blueberry, Mango]
UserInput = Mango
Output: The input found and the index number is 5
UserInput = Rice
Ouput: Input is not available in the array
INCORRECT SOLUTION:
FruitArray= ["Apple", "Orange", "Grape", "Strawberry", "Blueberry", "Mango"]
FruitSearch=input("Enter fruit to search")
c=0
while c<len(FruitArray):
if FruitArray[c]==FruitSearch:
print (FruitSearch, "found in index number", c)
if FruitArray[c]!= FruitSearch:
c = c + 1
print (FruitSearch, "is not available in the array")
****MY QUESTION: What to correct in the program to stop printing for infinite times if fruit is found?
One of possible solutions:
FruitArray= ["Apple", "Orange", "Grape", "Strawberry", "Blueberry", "Mango"]
FruitSearch=input("Enter fruit to search ")
c=0
while c<len(FruitArray):
if FruitArray[c]==FruitSearch:
print (FruitSearch, "found in index number", c)
break
c = c + 1
else:
print (FruitSearch, "is not available in the array")
You don't increase counter c in case a fruit is found.
Comments
Leave a comment