The counted loop
Show on a big screenA list holds three fares. How many times does a loop run?
- Positions 0 to 2 hold 9, 12, 15.
- i = 0. Fetch 9.
- i = 1. Fetch 12.
- i = 2. Fetch 15.
- i = 3. Test fails. Stop.
The rule
The loop runs its body three times, once for each fare. The body is the lines inside the loop.
A counted loop has three parts. Init makes the counter, once. Test checks before every turn. Update moves the counter, after every turn. The loop ends when the test says no.
| Part | When it runs |
|---|---|
| Init | Once, at the start |
| Test | Before every turn |
| Update | After every turn |
Here n is the number of fares, 3. The counter is i, a number that counts the turns. Each turn runs the body once. The name at is a variable name, not the English word. It holds the fare fetched last.
`` const fares = [9, 12, 15]; const n = fares.length; let at = 0; for (let i = 0; i < n; i = i + 1) { at = fares[i]; } print(at); ``
Each turn sets at to the fare at i: 9, 12, 15. This prints 15. The counter i ends at 3, one past the last position. The test asks "is 3 less than 3?" The answer is no, so the loop stops.
The test runs four times. The body runs three times.
Predict i and at after each line.
Loading lab…
Try the lab to finish this lesson.