Home »
Golang
Go Nested Loops
Last Updated : July 19, 2025
In Go, a loop inside another loop is called a nested loop. Nested loops are often used when working with things like tables (matrices) or when you need to repeat actions inside another set of repeated actions.
Syntax of Nested Loops
You can nest any loop inside another loop. The most common pattern is nesting for
loops:
for outerCondition {
for innerCondition {
// inner loop body
}
// outer loop body
}
Example: Nested Loop with Integers
Here's a simple example that prints a multiplication table using nested for
loops.
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
fmt.Printf("%d * %d = %d\t", i, j, i*j)
}
fmt.Println() // move to the next line after inner loop
}
}
When you run the above code, the output will be:
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3
2 * 1 = 2 2 * 2 = 4 2 * 3 = 6
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
Example: Looping Over a 2D Array
Nested loops are especially useful for accessing elements in a two-dimensional slice or array.
The following example demonstrates how to use nested loops in Go to iterate over a two-dimensional slice (matrix) and print its elements row by row:
package main
import "fmt"
func main() {
matrix := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[i]); j++ {
fmt.Printf("%d ", matrix[i][j])
}
fmt.Println()
}
}
When you run the above code, the output will be:
1 2 3
4 5 6
7 8 9
Breaking Out of Nested Loops
Use the break
statement inside the inner loop to stop only that loop. To break out of both inner and outer loops, you can use a label
.
Example
The following example shows how to use a labeled break statement in Go to exit from nested loops when a specific condition is met:
package main
import "fmt"
func main() {
outer:
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
if i*j > 4 {
break outer
}
fmt.Printf("%d * %d = %d\n", i, j, i*j)
}
}
}
When you run the above code, the output will be:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
The break outer
exits both loops once i * j > 4
.
Exercise
Test your knowledge of nested loops in Go:
- What is the output of the following loop?
for i := 1; i <= 2; i++ {
for j := 1; j <= 2; j++ {
fmt.Printf("%d-%d ", i, j)
}
}
- Which statement allows you to break out of both inner and outer loops?
- What is the correct way to access element at row 2, column 1 of a 2D slice
data
?
Advertisement
Advertisement