Putting a loop inside a loop
The body of a loop can hold any code, including another loop. This is called a nested loop. It is the natural tool for anything with rows and columns. The outer loop goes through the rows, and the inner loop goes through the columns of one row.
This program prints a small multiplication table:
package main
import "fmt"
func main() {
for row := 1; row <= 3; row++ {
for col := 1; col <= 4; col++ {
fmt.Printf("%3d", row*col)
}
fmt.Println()
}
}
Output:
1 2 3 4
2 4 6 8
3 6 9 12
%3d prints a number padded with spaces to 3 characters, so the columns line up.
For each round of the outer loop, the inner loop runs completely, from start to end. While row is 1, col goes 1, 2, 3, 4. Only then does row become 2, and the inner loop starts again from 1:
row | col goes | Printed |
|---|---|---|
| 1 | 1, 2, 3, 4 | 1 2 3 4 |
| 2 | 1, 2, 3, 4 | 2 4 6 8 |
| 3 | 1, 2, 3, 4 | 3 6 9 12 |
So fmt.Printf ran 3 × 4 = 12 times. Keep this in mind for larger inputs. If both loops run n times, the inner body runs n × n times. For n = 1000, that is a million rounds.
The counters are named row and col, not i and j. With two loops it is easy to mix the counters up, and clear names help.
Where a line goes matters
fmt.Println() sits inside the outer loop but after the inner loop, so it runs once per row and ends each line. A line inside the inner loop runs once per cell. A line outside both loops runs once. When a nested loop prints the wrong shape, check where each line sits.
The inner loop can also use the outer counter. Here it starts at row, so each row is shorter than the one before:
for row := 1; row <= 3; row++ {
for col := row; col <= 3; col++ {
fmt.Print(col)
}
fmt.Println()
}
Output:
123
23
3
break leaves only one loop
This program looks for two numbers from 1 to 4 whose product is 6. It means to stop at the first pair it finds:
for a := 1; a <= 4; a++ {
for b := 1; b <= 4; b++ {
if a*b == 6 {
fmt.Println("Found:", a, b)
break
}
}
}
fmt.Println("Done")
Output:
Found: 2 3
Found: 3 2
Done
It found two pairs. break ended only the inner loop, the one it is in. The outer loop went on with a = 3 and found 3 2.
To leave both loops, give the outer loop a label, a name followed by a colon, and write that name after break:
package main
import "fmt"
func main() {
outer:
for a := 1; a <= 4; a++ {
for b := 1; b <= 4; b++ {
if a*b == 6 {
fmt.Println("Found:", a, b)
break outer
}
}
}
fmt.Println("Done")
}
Output:
Found: 2 3
Done
break outer ends the loop named outer, and the program goes on after it. A label that is never used is a compile error, like an unused variable: label outer defined and not used.
In the exercise, read a number n and use a nested loop to print a triangle of stars with n rows, one star in the first row and one more in each row after it.