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.