OneBite.Dev - Coding blog in a bite size

implement a two nested loop in Go

Code snippet on how to implement a two nested loop in Go

package main
 
import "fmt"
 
func main() {
    outerLoopCount := 3
    innerLoopCount := 2
 
    for i := 1; i <= outerLoopCount; i++ {
        for j := 1; j <= innerLoopCount; j++ {
            fmt.Println("i =", i, "and j =", j)
        }
    }
}

This code will print a combination of values, created by two nested for-loops. The first for-loop is initialized with a variable “outerLoopCount” set to 3, which determines how many iterations the outer loop will make. The second for-loop is initialized with a variable “innerLoopCount” set to 2, which determines how many iterations the inner loop will make. For each iteration of the outer loop, the inner loop will start at 1 and will loop until it is equal to “innerLoopCount”. For each iteration of the inner loop, a statement will print the current values of “i” and “j”. Finally, the program will print all possible combinations of the two variables, which will be 6 in total: i = 1 and j = 1, i = 1 and j = 2, i = 2 and j = 1, i = 2 and j = 2, i = 3 and j = 1, and i = 3 and j = 2.

go