Go uses for for counted loops and while-style loops.

counted loop A counted `for` loop has an initializer, a condition, and an update step.

For Loops

limit
for_loop.go
Replay: real traced execution (multi-file project)
package main

import "fmt"

func main() {
	var limit = 4
	total := 0

	for number := 1; number <= limit; number++ {
		total += number
	}

	fmt.Println("limit=", limit)
	fmt.Println("total=", total)
}
package main

import "fmt"

func main() {
	var limit = 2
	total := 0

	for number := 1; number <= limit; number++ {
		total += number
	}

	fmt.Println("limit=", limit)
	fmt.Println("total=", total)
}
package main

import "fmt"

func main() {
	var limit = 6
	total := 0

	for number := 1; number <= limit; number++ {
		total += number
	}

	fmt.Println("limit=", limit)
	fmt.Println("total=", total)
}
  1. limit ← 4, total ← 0

    5func main() {6  var limit→ 4 = 4 //@limit=2, 67  total→ 0 := 0
  2. total ← 1

    pass 1 of 4
    9for number1 := 1; number <= limit4; number++ {10  total→ 1 += number111}
    All 4 passes — pass 1 is the card above
    passnumbertotal
    110 1
    221 3
    333 6
    446 10
  3. fmt.Println("limit=", limit)

    13  fmt.Println("limit=", limit4)14  fmt.Println("total=", total10)15}
    outputlimit= 4
    total= 10
  1. limit ← 2, total ← 0

    5func main() {6  var limit→ 2 = 27  total→ 0 := 0
  2. total ← 1

    pass 1 of 2
    9for number1 := 1; number <= limit2; number++ {10  total→ 1 += number111}
  3. total ← 3

    pass 2 of 2
    9for number2 := 1; number <= limit2; number++ {10  total→ 3 += number211}
  4. fmt.Println("limit=", limit)

    13  fmt.Println("limit=", limit2)14  fmt.Println("total=", total3)15}
    outputlimit= 2
    total= 3
  1. limit ← 6, total ← 0

    5func main() {6  var limit→ 6 = 67  total→ 0 := 0
  2. total ← 1

    pass 1 of 6
    9for number1 := 1; number <= limit6; number++ {10  total→ 1 += number111}
    All 6 passes — pass 1 is the card above
    passnumbertotal
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
  3. fmt.Println("limit=", limit)

    13  fmt.Println("limit=", limit6)14  fmt.Println("total=", total21)15}
    outputlimit= 6
    total= 21

Follow the Loop

  1. limit starts at 4.
  2. The loop visits 1, 2, 3, and 4.
  3. total adds each number as the loop moves forward.
  4. The final total is 10, so the program prints limit= 4 and total= 10. | number | running total | | --- | --- | | 1 | 1 | | 2 | 3 | | 3 | 6 | | 4 | 10 |

Exercise: for_loop.go

Reproduce the output lines limit= 4 and total= 10, then use the pinned limit variants to predict totals 3 and 21.