How can a school fair till add up sales without knowing how many there are?
At a school fair in Leeds, you need to add up the prices on all the receipts. The pile might have two receipts, fifty, or none at all. How can the till know when to stop without counting the receipts first?
A count-controlled loop can print a set number of tickets. You could name that fixed number TICKET_COUNT and give it the value five. An IF statement checks a condition before acting. For example, you print a ticket only if the payment has gone through.
The till asks whether there’s an unread receipt. There’s one left, so the answer is yes. It reads that receipt and adds its price. Then it asks the same question again. This time the answer is no, so it stops without trying to read anything else.
This time the pile is empty at the start. The instructions that read a receipt and add its price are called the loop body. Think about the answer to the first check. How many times does the body run? Pick an answer.
This is a pre-condition loop. In a WHILE loop, you test the condition before each pass through the body. Here, a Boolean flag called entryAvailable holds true or false. It tells you whether there’s another entry, so you don’t need a fixed count.
Set the running total to zero. Call has next to check for an unread receipt and store its answer in the flag. While the flag is true, call read next price to take one receipt from the pile, then add its price. Call has next again to refresh the flag.
With two receipts, the flag starts true, so you enter. Add three pounds. The flag stays true, so you enter again and add five pounds. The flag becomes false. The next test fails, leaving eight pounds. With an empty pile, the first test fails, so the total stays at zero.
Now try a pile with receipts for four pounds and six pounds, in that order. Pause just after processing the first receipt and updating the flag. What are the total and the value of the flag at that point? Pick an answer.
Both versions start with the flag set before the loop. If you leave out the update, the flag stays true after the last receipt, and the till tries to read from an empty pile. If you refresh the flag after reading, the next test sees false when the pile is empty.
Try this Paper One style question: explain why this loop never stops. Start with the value: ready is true. Then point to the body: displaying a message never changes ready. Link those facts in your answer: the condition stays true, so the message is displayed over and over.