Foundations
Loops
Go uses for for counted loops, range loops, and while-style loops.
for loop
Go uses `for` as its only loop keyword.
Loops
loop_intro.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)
}
limit ← 4, total ← 0
5func main() {6 var limit→ 4 = 4 //@limit=2, 67 total→ 0 := 0total ← 1
pass 1 of 49for number1 := 1; number <= limit4; number++ {10 total→ 1 += number111}All 4 passes — pass 1 is the card above pass numbertotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 fmt.Println("limit=", limit)
13 fmt.Println("limit=", limit4)14 fmt.Println("total=", total10)15}outputlimit= 4 total= 10
limit ← 2, total ← 0
5func main() {6 var limit→ 2 = 27 total→ 0 := 0total ← 1
pass 1 of 29for number1 := 1; number <= limit2; number++ {10 total→ 1 += number111}total ← 3
pass 2 of 29for number2 := 1; number <= limit2; number++ {10 total→ 3 += number211}fmt.Println("limit=", limit)
13 fmt.Println("limit=", limit2)14 fmt.Println("total=", total3)15}outputlimit= 2 total= 3
limit ← 6, total ← 0
5func main() {6 var limit→ 6 = 67 total→ 0 := 0total ← 1
pass 1 of 69for number1 := 1; number <= limit6; number++ {10 total→ 1 += number111}All 6 passes — pass 1 is the card above pass numbertotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 fmt.Println("limit=", limit)
13 fmt.Println("limit=", limit6)14 fmt.Println("total=", total21)15}outputlimit= 6 total= 21
Follow the Loop
limitstarts at4.totalstarts at0.- The loop adds
1, then2, then3, then4. totalbecomes10.- The program prints
limit= 4andtotal= 10. | limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
Exercise: loop_intro.go
Reproduce total= 10 for limit 4, then try limit 2 and 6 and predict each total before running it.