Skip to content
Exit presentation

Programming Proper II: Functions, Lists & Simple Algorithms

The counted loop

A list holds three fares. How many times does a loop run?

Positions 0 to 2 hold 9, 12, 15.
Step 1 of 5
  1. Positions 0 to 2 hold 9, 12, 15.
  2. i = 0. Fetch 9.
  3. i = 1. Fetch 12.
  4. i = 2. Fetch 15.
  5. 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.

The three parts of a counted loop
PartWhen it runs
InitOnce, at the start
TestBefore every turn
UpdateAfter 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…

Jump to lesson

This track

  1. 0 Start here
  2. 1 Is it there at all?
  3. 2 The counted loop
  4. 3 In order first
  5. 4 Counting both searches
  6. 5 One pass, and the box in the middle
  7. 6 The whole sort, written down
  8. 7 Sort once, search many
  9. 8 How the count grows
  10. 9 The big picture
  11. 10 Track quiz

Other tracks