asked 227k views
5 votes
Tiffany is writing a program to help manage a bake sale. She writes the following code which prompts the user to enter the total number of items a person is buying and then a loop repeatedly prompts for the cost of each item. She wrote the code but there is a problem: it runs in an infinite loop. How can Tiffany change her code so it doesn't loop forever?

0 var numItems = promptNum("How many items?");
1 var total = 0;
2 while (numItems > 0){
3 total = total + promptNum("Enter next item price");
4 }
5 console.log("The total is" + total);

asked
User Csalive
by
8.0k points

1 Answer

3 votes

Answer:

Add the line numItems=numItems-1 after the 3rd code line.

Step-by-step explanation:

As the loop is not terminating thus the counter is to be added such that the value is decreased in each iteration. As the last item is entered the value will become 0. Now when the loop will again reach the while point, the condition will become false and thus the loop will be terminated.

answered
User Greyisf
by
7.9k points
Welcome to Qamnty — a place to ask, share, and grow together. Join our community and get real answers from real people.