75.8k views
4 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);
Add after line 3: numItems = numItems - 1;

What value will be displaye

1 Answer

6 votes

Answer:

Step-by-step explanation:

the answer is also in the question. The loop is used to control the number of program execution. So in order not to run forever, the loop should be included inside the loop brackets. Then you can restructure the code as done below.

var numItems = promptNum("How many items?");

var total = 0;

var itemPrice=0;

while (numItems > 0){

itemPrice = promptNum("Enter next item price");

total = total + itemPrice;

numItems = numItems - 1;

}

console.log("The total is" + total);

The value to be displayed will be the total of the item prices inputted.

User NoEmbryo
by
5.0k points