One box outside the loop
The register holds six counts of plates. The cook wants one number, not six.
Loading lab…
Step 1 of 7
- Before the loop: total = 0.
- 6A adds 28. Total = 28.
- 6B adds 31. Total = 59.
- 7A adds 26. Total = 85.
- 7B adds 24. Total = 109.
- 8A adds 30. Total = 139.
- 8B adds 27. Total = 166.
The rule
Add the six counts to get one total, 166. A loop repeats the same lines once for each count.
One box sits outside the loop. One line inside it adds each item on. That pair turns a whole list into one total.
let total = 0;— the box, made before the loop.total = total + count;— the line, inside the loop.return total;— after the loop, the box holds the total.
A turn is one pass of the loop. The box must exist before the first turn. Then every turn adds onto something already there.
An empty register still works. The loop has no turns, so the box stays at 0.
Watch out!
total = count; replaces the total. Then the run prints 27, the last count. Add each count to the box.