Counting with Go's only loop
A loop runs the same code many times. Without one, printing the numbers 1 to 100 would take 100 lines. Many languages have several kinds of loop, with names like while and do. Go has only one: for. This lesson shows the counting form, and the next lesson shows the other forms.
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println("Round", i)
}
fmt.Println("Finished")
}
Output:
Round 1
Round 2
Round 3
Finished
The line after for has three parts, with semicolons between them:
| Part | Code | When it runs |
|---|---|---|
| start | i := 1 | once, before the loop begins |
| condition | i <= 3 | before every round; the loop ends when it is false |
| step | i++ | after every round |
i++ adds 1 to i. So the loop goes like this: set i to 1, check i <= 3, run the body, add 1, check again, and so on. When i becomes 4, the condition is false and Go moves on to the line after the loop. Each pass through the body is called an iteration, or a round.
The step can be anything. i-- subtracts 1, so this loop counts down. i += 2 adds 2, so the next one counts in twos:
for i := 3; i >= 1; i-- {
fmt.Println(i)
}
for i := 0; i <= 6; i += 2 {
fmt.Println(i)
}
Output:
3
2
1
0
2
4
6
Adding up in a loop
A very common use of a loop is a running total. Start a variable at 0 before the loop, and add to it in every round:
sum := 0
for i := 1; i <= 5; i++ {
sum += i
}
fmt.Println("Sum:", sum)
Output:
Sum: 15
sum is declared before the loop, so it keeps its value from round to round, and you can print it after the loop. i is different. It is created by the loop and exists only inside it. Printing i after the loop gives the compile error undefined: i.
Counting with range
Go 1.22 added a shorter form. for i := range 5 runs 5 times, with i going from 0 to 4:
for i := range 5 {
fmt.Print(i, " ")
}
fmt.Println()
Output:
0 1 2 3 4
fmt.Print prints without a new line, and the empty fmt.Println() ends the line at the end. The count always starts at 0, and the number after range is never reached. If you do not need i at all, write for range 5.
Check the edges
Many loop bugs run one round too many or one too few. i < 5 stops before 5, and i <= 5 includes it. Starting at 0 or at 1 also changes how many rounds run. When a loop prints one value too many or too few, look at the start and the condition first.
In the exercise, read a number n and finish the condition of a loop that prints the order IDs from 1001 up to 1000 + n.