VCF

Unit 4 · Thinking like a programmer

How many times does a for loop run?

Count the values i takes while the condition is true. let i = 0; i < 4 runs with 0, 1, 2 and 3: four passes. At 4 the check fails and the loop ends.

The mix-up

What people often think

“i < 4 runs the body once more, or once less, than four times.”

What the tutor says

Count the values i takes while the check is true: 0, 1, 2, 3. That is four passes. At 4 the check fails and the loop ends.

Write down each value of i next to a tick for each pass. How many ticks?

How it works

A loop starts wherever its first part says, not always at 0 or 1. To print 1 to 10, start at 1 and keep going while i <= 10 (or i < 11). i < 10 stops after 9.

Write the values of i down with a tick for each pass. It takes ten seconds and catches almost every off-by-one error.

Side by side

The mix-upJavaScript
for (let i = 1; i < 10; i++) {
  console.log(i);  // 1 to 9
}
Stops one short.
What worksJavaScript
for (let i = 1; i <= 10; i++) {
  console.log(i);  // 1 to 10
}
Includes 10.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “i < 10 includes 10.”

    < means strictly less than, so the loop stops after 9. Use i <= 10, or i < 11.

  • “Loops always start counting at 1.”

    A loop starts wherever its first part says. Here let i = 0, so the first pass uses 0.

  • “Every loop has to start at 0.”

    Starting at 0 logs 0 first. You choose the start, so start at 1.

Practise it with a tutor watching

Loops: doing it again

Trace a loop pass by pass, write one that counts, and fix one that stops a step early.

20 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.