Go · Stage 4 – Repeating Things · Lesson 29 of 64

Common Loop Mistakes

Recognize endless loops and boundary errors.

Go code

for i := 0; i < 3; i++ {
    fmt.Println(i)
}
Line-by-line explanation
  1. I starts at zero.
  2. The condition allows values below 3.
  3. The output is 0, 1, and 2—not 3.
Expected output
0
1
2

This is the expected result.

A condition-only loop also becomes infinite when its controlling value never changes. Use Ctrl+C in a terminal to interrupt a stuck program.

Tiny Practice

Starter scenario

Fix the loop so it runs three times.

Go code

for i := 0; i CHANGE_ME 3; i++ {
    fmt.Println(i)
}
Line-by-line explanation
  1. The comparison symbol is missing.
  2. Start at zero and stop before 3.
Expected output
(complete the starter first)

The starter intentionally contains CHANGE_ME.

Hint
  1. Use <.
  2. Do not use <=.
  3. Expect 0, 1, 2.
Show Solution

Go code

for i := 0; i < 3; i++ {
    fmt.Println(i)
}
Line-by-line explanation
  1. The boundary excludes 3.
  2. Exactly three values are displayed.
Expected output
0
1
2

This is the expected result.