Go, lesson 5
Go has exactly one looping keyword: for. It covers everything other languages split into
for, while and do-style loops, just written in different shapes.
The classic form has three parts separated by semicolons: a start statement, a condition checked before each pass, and a post statement run after each pass.
The variable i exists only inside the loop. Each pass gets its own copy of i, which
matters when you capture it in a function later.
Since Go 1.22 you can range over an integer. for i := range n runs n times with i going
from to . If you do not need the counter at all, leave it out:
2 exercises to try what you just read.
0n-1Drop the start and post statements and keep only the condition. The loop runs while the condition stays true:
With no condition at all, for { ... } loops until something inside stops it. This is the
natural shape for "keep reading until there is no more input":
fmt.Scan returns an error when the input runs out, so err != nil is your signal to stop.
The same idea works with a bufio.Scanner: for sc.Scan() { ... } runs once per line and
stops at the end of the input.
break leaves the loop immediately.continue skips the rest of this pass and starts the next one.When loops are nested, break only leaves the innermost one. To leave an outer loop, put a
label in front of it and name it: break outer.
A common loop pattern is to start a variable at a neutral value (0 for a sum, 1 for a
product) and update it on every pass. Keep that variable outside the loop, so it survives
from one pass to the next.
Read a whole number n and print its times table from 1 to 10, one line each, in the form
n x i = result.
Sample input:
Sample output (first and last lines shown):
You save money every week. Read numbers (weekly deposits) until the input runs out, adding
them up. As soon as the running total reaches 100 or more, print goal reached in week N
(where week 1 is the first number) and stop reading. If the input ends first, print
total so far: T.
Sample input:
Sample output:
for i := 1; i <= 3; i++ {
fmt.Println("lap", i)
}
// lap 1
// lap 2
// lap 3for i := range 3 {
fmt.Println(i) // 0, 1, 2
}
for range 2 {
fmt.Println("beep")
}balance := 100
for balance > 0 {
balance -= 30
}
fmt.Println(balance) // -20for {
var n int
if _, err := fmt.Scan(&n); err != nil {
break // no more numbers
}
fmt.Println("got", n)
}for i := range 10 {
if i%2 == 0 {
continue // skip even numbers
}
if i > 7 {
break // stop after 7
}
fmt.Print(i, " ")
}
// 1 3 5 7outer:
for r := range 3 {
for c := range 3 {
if r*c == 2 {
break outer
}
}
}77 x 1 = 7
7 x 2 = 14
...
7 x 10 = 7030 25 40 10 50goal reached in week 4