Lesson 7 / 27

The for loop

Explain The for loop, test a small program, and use the result to build confidence.

The essential idea

The for loop becomes clear when you identify its job before memorising syntax. In Go, small explicit pieces combine into programs that are easy to read, build, and change.

Trace each loop pass

Keep the path from source file to compiled program in mind as you learn this part.

sum := 0
for n := 1; n <= 3; n++ {
  sum += n
}
fmt.Println(sum)

Output:

6
  1. Line 1: The running total exists before the loop starts.
  2. Line 2: The first valid n enters the loop body.
  3. Line 3: The body changes the accumulated value.
  4. Line 5: After the last pass, the final total prints once.

A useful habit

Do not copy a solution blindly. For The for loop, change one value, run go test or go run, and explain why the result changed.

Quick check

Quick check: How should you learn The for loop?

  • Run one focused example and inspect the result.
  • Memorize it without writing code.
  • Skip compiler and test feedback.
Answer

Run one focused example and inspect the result. — Small experiments reveal cause and effect.