Gaaker Go

Golang Nested for loop

For loops can also be nested.

Pay attention to the order in which the sample code runs.

The following is a complete code example.

package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        fmt.Printf("Outer loop iteration %d start\n", i)
        for j := 0; j < 2; j++ {
            fmt.Printf("i= %d j=%d\n", i, j)
        }
		fmt.Printf("Outer loop iteration %d end\n", i)
    }
}

Below is the program output:

Outer loop iteration 0 start
i= 0 j=0
i= 0 j=1
Outer loop iteration 0 end
Outer loop iteration 1 start
i= 1 j=0
i= 1 j=1
Outer loop iteration 1 end
Outer loop iteration 2 start
i= 2 j=0
i= 2 j=1
Outer loop iteration 2 end
< Nested for loop Nested for loop >