Skip to content
Your progress

Checking your sign-in…

Who's learning?

Each profile keeps its own read lessons, badges, streak, and practice scores on this device.

Lesson 2 of 11

The counted loop

Show on a big screen

7 min

Text size

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…

Try the lab to finish this lesson.