SyntaxPilot
Courses/Go Programming/Lesson 8

Go Programming · Lesson 8 of 89 · 12 min

Loops: the many faces of for

three-component for loopcondition-only for (while style)infinite forbreakcontinuelabelslabelled break and continuegotofor range over integers (Go 1.22)range over slices and strings (preview)per-iteration loop variables (Go 1.22)

These are the notes for Go episode 8. Last episode your programs learned to decide; today they learn to repeat. Repeating a block of code is called a loop, and Go has exactly one loop keyword: for. You will learn the three-part for loop, the condition-only for (Go's "while"), infinite loops (the bug and the deliberate kind), break and continue, labels with labelled break and continue, goto (and why it's rare), for range over integers (new in Go 1.22), a first look at range over slices and strings, and Go 1.22's per-iteration loop variables. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).

Words used all the way through:

  • A loop repeats a block of code.
  • One pass through the loop's body is an iteration. A loop that prints 10 lines runs 10 iterations.
  • The loop variable is the variable that changes each iteration and usually counts them, like i.
  • The body is the block inside the loop's braces: the code that repeats.

The problem: the 7 times table, by hand

Write the 7 times table. With what we know, that's one print line per row, typed by hand:

package main

import "fmt"

func main() {
    fmt.Println("7 x 1 = 7")
    fmt.Println("7 x 2 = 14")
    fmt.Println("7 x 3 = 21")
    fmt.Println("7 x 4 = 28")
    fmt.Println("7 x 5 = 35")
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

It works, but we typed every answer ourselves; the computer isn't calculating anything. Up to 7 × 1000 would be a thousand nearly identical lines, with a typo hiding somewhere. The lines differ in only one number, so let a variable hold that number and repeat the same line.

The three-part for loop

package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        fmt.Println("7 x", i, "=", 7*i)
    }
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

for init; condition; post { body }:

Part Here When it runs
init statement i := 1 once, before everything
condition i <= 10 before every iteration; false ends the loop
body fmt.Println(...) each iteration, while the condition is true
post statement i++ after every iteration, before the next condition check

Step by step: i starts at 1 → is 1 <= 10? yes → print 7 x 1 = 7 → i++ makes 2 → is 2 <= 10? yes → print ... → after printing 7 x 10 = 70, i++ makes 11 → is 11 <= 10? no → the loop ends. That's 10 iterations. Change 10 to 1000 and the same three lines print a thousand rows.

Notes:

  • No round brackets around the three parts, and the braces are required (same as if).
  • Any of the three parts can be left out, which gives the other faces of for below.
  • Counting down works too: for i := 10; i >= 1; i-- { ... }. Steps of 2: i += 2 in the post statement.

The loop variable lives only inside the loop

package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        fmt.Println(i)
    }
    fmt.Println("last:", i)
}
# command-line-arguments
./main.go:9:26: undefined: i

Like an if init statement, a variable created in the for init statement has block scope: it exists only inside the loop. If you need the final value afterwards, declare the variable before the loop (i := 1 then for ; i <= 3; i++ {).

for as a while loop

You want a Rs 20,000 phone and save Rs 1,500 a month. How many months? This time we don't know how many iterations we need; we keep going while the savings are below 20,000. Many languages have a while keyword for this. Go doesn't:

package main

import "fmt"

func main() {
    saved, months := 0, 0
    while saved < 20000 {
        saved += 1500
        months++
    }
    fmt.Println(months)
}
# command-line-arguments
./main.go:7:11: syntax error: unexpected name saved at end of statement
./main.go:11:5: syntax error: non-declaration statement outside function body

Go sees while as a plain name (an identifier), so the line doesn't make sense to it. In Go you write for with only a condition: no init, no post. It means exactly what while means elsewhere:

package main

import "fmt"

func main() {
    saved, months := 0, 0
    for saved < 20000 {
        saved += 1500
        months++
    }
    fmt.Println(months, "months, saved", saved)
}
14 months, saved 21000

13 months gives only 19,500, so it takes 14 months (21,000).

Infinite loops

The bug: nothing moves the loop towards its end

package main

import "fmt"

func main() {
    saved, months := 0, 0
    for saved < 20000 {
        months++ // forgot: saved += 1500
    }
    fmt.Println(months)
}
Time Limit Exceeded

saved stays 0, so saved < 20000 is always true and the loop never ends. That's an infinite loop. The SyntaxPilot compiler stops a program after 8 seconds and shows Time Limit Exceeded; on your own computer it would run until you press Ctrl+C. Every loop needs something inside that moves it towards its end.

On purpose: for { } and break

Sometimes "forever" is exactly right: a server waits for requests forever, a game runs until the player quits. Write for with nothing at all, and leave with break, which ends the loop immediately; the program continues after the loop.

A shop gives a gift to the first token number divisible by both 7 and 11:

package main

import "fmt"

func main() {
    n := 1
    for {
        if n%7 == 0 && n%11 == 0 {
            break
        }
        n++
    }
    fmt.Println("lucky token:", n)
}
lucky token: 77

We didn't know where the answer was, so the stop test sits in the middle of the body. The loop ran 77 times and break stopped it at the right moment. (77 = 7 × 11, the least common multiple.)

continue: skip one iteration

A bus has seats 1 to 10; seats 4 and 7 are broken:

package main

import "fmt"

func main() {
    for seat := 1; seat <= 10; seat++ {
        if seat == 4 || seat == 7 {
            continue // broken seats
        }
        fmt.Print(seat, " ")
    }
}
1 2 3 5 6 8 9 10 

continue skips the rest of the current iteration and goes straight to the next one. In a three-part loop the post statement (seat++) still runs. Remember: break leaves the loop; continue skips one turn.

Nested loops and labels

A loop inside a loop is a nested loop: for every iteration of the outer loop, the inner loop runs completely. Two dice, a and b, each 1 to 6. We want the first pair that adds up to 9:

package main

import "fmt"

func main() {
    for a := 1; a <= 6; a++ {
        for b := 1; b <= 6; b++ {
            if a+b == 9 {
                fmt.Println(a, "+", b)
                break
            }
        }
    }
}
3 + 6
4 + 5
5 + 4
6 + 3

Four pairs! break leaves only the innermost loop. The outer loop simply moved on to the next a and found more pairs.

Labels: name the loop you mean

A label is a name followed by a colon, written just before a statement. break outer leaves the loop labelled outer, so both loops at once:

package main

import "fmt"

func main() {
    outer:
    for a := 1; a <= 6; a++ {
        for b := 1; b <= 6; b++ {
            if a+b == 9 {
                fmt.Println(a, "+", b)
                break outer
            }
        }
    }
    fmt.Println("found it")
}
3 + 6
found it
  • break label ends the labelled loop.
  • continue label jumps to the next iteration of the labelled loop (the outer loop's post statement runs, then its condition).
  • Labels fix last episode's puzzle too: break inside a switch inside a loop leaves only the switch; break outer leaves the loop.

A labelled continue: for each row, print numbers until the product passes 6, then move to the next row:

package main

import "fmt"

func main() {
row:
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 5; j++ {
            if i*j > 6 {
                fmt.Println("| row", i, "done")
                continue row
            }
            fmt.Print(i*j, " ")
        }
        fmt.Println("| row", i, "finished all")
    }
}
1 2 3 4 5 | row 1 finished all
2 4 6 | row 2 done
3 6 | row 3 done

gofmt puts labels at the start of the line, one level less indented than the code. Labels have their own namespace, so a label can share a name with a variable.

An unused label is an error

package main

import "fmt"

func main() {
outer:
    for i := 0; i < 3; i++ {
        fmt.Println(i)
    }
}
# command-line-arguments
./main.go:6:1: label outer defined and not used

Like unused variables and imports, Go refuses a label you never use.

goto

Labels have one more use: goto label jumps straight to that label, anywhere in the same function.

package main

import "fmt"

func main() {
    goto done
    x := 5
    fmt.Println(x)
    done:
    fmt.Println("end")
}
# command-line-arguments
./main.go:6:10: goto done jumps over declaration of x at ./main.go:7:7

Go won't let goto jump over a variable declaration (or into a block), because code after the label could then use a variable that was never set up. goto is legal and has rare legitimate uses, but jumping around makes programs hard to follow. In everyday Go, use loops, break, continue and functions instead.

A legal goto, just to see one:

package main

import "fmt"

func main() {
    n := 1
again:
    fmt.Print(n, " ")
    n++
    if n <= 3 {
        goto again
    }
    fmt.Println("- that was a loop made with goto. Use for instead!")
}
1 2 3 - that was a loop made with goto. Use for instead!

range: let Go do the counting

Over an integer (Go 1.22)

package main

import "fmt"

func main() {
    for i := range 5 {
        fmt.Print(i, " ")
    }
    fmt.Println()
    for range 3 {
        fmt.Println("hip hip hooray!")
    }
}
0 1 2 3 4 
hip hip hooray!
hip hip hooray!
hip hip hooray!
  • for i := range 5 gives i the values 0, 1, 2, 3, 4: five values, starting at 0, stopping before 5. It's the same as for i := 0; i < 5; i++.
  • for range 3 repeats three times when you don't need the number.
  • Ranging over an integer is new: the Go 1.22 release notes say "For loops may now range over integers", and Go 1.22 was announced on 6 February 2024. Older tutorials don't show it.

Over a slice and a string (preview)

package main

import "fmt"

func main() {
    names := []string{"Asha", "Ravi", "Meena"}
    for i, name := range names {
        fmt.Println(i, name)
    }
    for i, ch := range "chai" {
        fmt.Println(i, string(ch))
    }
}
0 Asha
1 Ravi
2 Meena
0 c
1 h
2 a
3 i
  • []string{"Asha", "Ravi", "Meena"} is a slice: a list of values of one type (here strings). Slices get two full episodes (13 and 14).
  • range over a slice gives two values each iteration: the index (the position, starting at 0) and the value at that position.
  • Don't need the index? Use the blank identifier: for _, name := range names. Need only the index? for i := range names.
  • range over a string gives each character with its byte position. string(ch) turns the character back into a one-letter string for printing. With non-English letters the positions jump, because some characters take more than one byte; episode 17 explains why.

One variable per iteration (Go 1.22)

Imagine a teacher who writes the round number on one shared whiteboard, wiping it every round. Students who photograph the board later all see only the final number. Go loops used to work like that: one loop variable, reused for every iteration. The problem only shows when you save something that looks at the variable later, after the loop has moved on.

func() { ... } below is a small function stored in a variable, to run later (episode 10 explains these fully). With the variable declared once, outside the loop:

package main

import "fmt"

func main() {
    var later []func()
    var i int
    for i = 0; i < 3; i++ {
        later = append(later, func() { fmt.Print(i, " ") })
    }
    for _, f := range later {
        f()
    }
}
3 3 3 

All three saved functions look at the same i, and by the time they run, the loop has pushed it to 3. Before Go 1.22, even for i := 0; ... behaved this way, and it caused real bugs (especially with goroutines, which you'll meet in the concurrency episodes).

Since Go 1.22, each iteration gets its own fresh copy of the loop variable. In the release notes' words: "In Go 1.22, each iteration of the loop creates new variables, to avoid accidental sharing bugs."

package main

import "fmt"

func main() {
    var later []func()
    for i := 0; i < 3; i++ {
        later = append(later, func() { fmt.Print(i, " ") })
    }
    for _, f := range later {
        f()
    }
}
0 1 2 

Each saved function remembers its own i. (The new behaviour applies to code whose module says go 1.22 or later in its go.mod; the examples here were run without a go.mod, which uses the newest rules.)

The faces of for

Form Example Like
three-part for i := 1; i <= 10; i++ { } the classic counting loop
condition only for saved < 20000 { } while in other languages
infinite for { ... break ... } while (true)
range over an int for i := range 5 { } count 0 to 4
range, no variable for range 3 { } repeat 3 times
range over a slice for i, v := range list { } for-each
range over a string for i, ch := range "chai" { } each character

Common mistakes (and the real error messages)

You wrote Real error Fix
while saved < 20000 { syntax error: unexpected name saved at end of statement for saved < 20000 {
a loop that never changes its condition Time Limit Exceeded (runs forever) move towards the end inside the loop
fmt.Println(i) after for i := ... undefined: i declare i before the loop
break in an inner loop, expecting both to stop no error: the outer loop continues a label: break outer
a label you never use label outer defined and not used use it or delete it
goto done over x := 5 goto done jumps over declaration of x at ./main.go:7:7 avoid goto; restructure
for i := range 5 expecting 1 to 5 no error: prints 0 to 4 i+1, or for i := 1; i <= 5; i++
i <= len vs i < len mix-ups off by one: one iteration too many or too few trace the first and last iteration

Mini project: the digits of a number

How many digits does 9876 have, and what do they add up to? Last episode's trick: n % 10 is the last digit, n / 10 chops it off.

package main

import "fmt"

func main() {
    // Mini project: the digits of a number
    n := 9876
    digits, sum := 0, 0
    for n > 0 {
        sum += n % 10
        n /= 10
        digits++
    }
    fmt.Println("digits:", digits, "sum:", sum)
}
digits: 4 sum: 30

We don't know in advance how many digits there are, so it's a condition-only loop. Trace: 9876 → +6, 987 → +7, 98 → +8, 9 → +9, 0 → stop. 4 digits, sum 30.

Practice

  1. Print the 13 times table from 13 × 1 to 13 × 20.
  2. How many months to save Rs 1,00,000 at Rs 2,500 a month?
  3. Print 1 to 50, skipping multiples of 3, on one line.
  4. Reverse a number: 9876 → 6789.
Solutions and hints
  1. A three-part loop:
package main

import "fmt"

func main() {
    for i := 1; i <= 20; i++ {
        fmt.Println("13 x", i, "=", 13*i)
    }
}
13 x 1 = 13
13 x 2 = 26
13 x 3 = 39
13 x 4 = 52
13 x 5 = 65
13 x 6 = 78
13 x 7 = 91
13 x 8 = 104
13 x 9 = 117
13 x 10 = 130
13 x 11 = 143
13 x 12 = 156
13 x 13 = 169
13 x 14 = 182
13 x 15 = 195
13 x 16 = 208
13 x 17 = 221
13 x 18 = 234
13 x 19 = 247
13 x 20 = 260
  1. A condition-only loop:
package main

import "fmt"

func main() {
    saved, months := 0, 0
    for saved < 100000 {
        saved += 2500
        months++
    }
    fmt.Println(months, "months")
}
40 months
  1. continue on multiples of 3:
package main

import "fmt"

func main() {
    for i := 1; i <= 50; i++ {
        if i%3 == 0 {
            continue
        }
        fmt.Print(i, " ")
    }
    fmt.Println()
}
1 2 4 5 7 8 10 11 13 14 16 17 19 20 22 23 25 26 28 29 31 32 34 35 37 38 40 41 43 44 46 47 49 50 
  1. Take the last digit off n and push it onto rev:
package main

import "fmt"

func main() {
    n, rev := 9876, 0
    for n > 0 {
        rev = rev*10 + n%10
        n /= 10
    }
    fmt.Println(rev)
}
6789

Quick quiz

What does this print (inside main)?

for i := range 6 {
    if i == 4 {
        break
    }
    if i%2 == 0 {
        continue
    }
    fmt.Print(i)
}
  • A. 13
  • B. 135
  • C. 024
  • D. 1
Answer

A. 13. range 6 gives 0 to 5. Even numbers (0 and 2) are skipped by continue. At 4, break ends the loop, so 5 never gets a turn. Only 1 and 3 print.

Interview questions

  • How many loop keywords does Go have? How do you write a while loop and an infinite loop?
  • Describe the order in which the init, condition, body and post statement of a for loop run.
  • What's the difference between break and continue? Which loop does break leave in nested loops?
  • What is a label? Show break outer and continue outer.
  • Why does Go refuse goto over a variable declaration? When, if ever, is goto reasonable?
  • What does for i := range 5 produce? Which Go version added it?
  • What changed about loop variables in Go 1.22, and what bug did it fix?
  • What does range give you over a slice? Over a string?

Glossary

Term Meaning Example
Loop code that repeats a block for i := 1; i <= 10; i++ { }
Iteration one pass through the loop body 10 iterations print 10 rows
Body the block inside the loop's braces fmt.Println(...)
Loop variable the variable that changes each iteration i
for Go's only loop keyword for {
Init statement runs once before the loop starts i := 1
Condition checked before every iteration; false ends the loop i <= 10
Post statement runs after every iteration i++
Condition-only for for cond { }: Go's while loop for saved < 20000 {
while (other languages) a loop that repeats while a condition is true; not a Go keyword while (x < 5) in C
Infinite loop a loop that never ends for { }
Time Limit Exceeded the online compiler stopped a program that ran too long (8 s) the forgotten saved += 1500
Ctrl+C the key combination that stops a running program in a terminal
break ends the innermost loop (or switch) right now "lucky token: 77"
continue skips the rest of this iteration, starts the next one broken seats
Nested loop a loop inside another loop two dice
Innermost loop the loop closest around a statement where plain break acts
Label a name and a colon before a statement outer:
Labelled break break name: ends the labelled loop break outer
Labelled continue continue name: next iteration of the labelled loop continue row
goto jumps to a label in the same function; rarely used goto done
Scope / block scope where a name exists; loop variables exist only in the loop undefined: i
range walks through a number, slice, string (and more), giving values one by one for i := range 5
Range over an integer counts from 0 up to, not including, the number (Go 1.22) range 5 → 0..4
Slice a list of values of one type (episodes 13-14) []string{"Asha", "Ravi"}
Index a position in a list, starting at 0 names[0] is "Asha"
Blank identifier _ a placeholder for a value you don't need for _, v := range list
Byte position where a character starts inside a string, counted in bytes 0 c, 1 h
Per-iteration loop variable since Go 1.22, each iteration gets a fresh copy of the loop variable prints 0 1 2, not 3 3 3
Function literal a function written inline without a name; stored to run later (episode 10) func() { fmt.Print(i) }
go.mod go line the Go version a module is written for; decides some language rules go 1.22
Off-by-one error a loop that runs one time too many or too few <= vs <
Least common multiple the smallest number divisible by both 77 for 7 and 11

Summary

  • for init; condition; post { } is the classic loop: init once, then condition → body → post, until the condition is false. The loop variable lives only in the loop.
  • for condition { } is Go's while; for { } runs forever until break. Every loop must move towards its end.
  • break leaves the innermost loop; continue skips to the next iteration. Labels (break outer, continue outer) reach an outer loop. Unused labels are errors.
  • goto exists but is rarely the right tool, and can't jump over declarations.
  • range counts for you: range 5 gives 0 to 4 (Go 1.22); over a slice it gives index and value; over a string, position and character.
  • Since Go 1.22, every iteration has its own loop variable, so saved functions see 0 1 2, not 3 3 3.

Next episode: functions. A GST bill copied into three shops, a bug fixed in only one of them, and you'll invent functions: parameters, multiple results, variadic functions and functions as values.