Answer to Question #290687 in Python for ggfh

Question #290687

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?


1
Expert's answer
2022-01-25T16:19:59-0500

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.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS