Use nested loops and labels
Use nested loops and labels
A nested loop is a loop inside another loop. For each outer iteration the inner loop starts again. A label is a name followed by a colon before a statement. A labeled break or continue can target an enclosing loop instead of the nearest loop.
package main
import "fmt"
func main() { for row := 1; row <= 2; row++ { for col := 1; col <= 3; col++ { fmt.Println(row, col) } }}Two rows with three columns give six pairs. The inner counter is initialized again for each row. An unlabeled break inside the inner loop would end only that loop.
Exit both loops after a match
package main
import "fmt"
func main() {Search: for row := 1; row <= 3; row++ { for col := 1; col <= 3; col++ { if row*col == 4 { fmt.Println("found:", row, col) break Search } } }}break Search exits the outer loop, so no more pairs are examined. continue Search would instead advance to the next outer iteration. Labels must identify an appropriate enclosing statement; do not jump to a sibling loop with break or continue. Use descriptive labels sparingly.
Try it locally
For rows 1 to 3 and columns 1 to 2, print pairs, but use a labeled continue to skip the rest of row 2 before printing any pair in that row. Expected: 1 1, 1 2, 3 1, 3 2 on separate lines.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loops 04: Use nested loops and labels
Check the lesson objective before moving on.
How many pairs are produced by 2 outer and 3 inner iterations without early exits?
What does break Search do in the example?