13.Loop - Nested Loops - Programming in GO

Posted on Mar 06, 2019   ∣  1 min read  ∣  GO

Loop - Nested Loops

Now, we’re going to see a loop within a loop. There will be an outer loop, and it will run however many times it runs, and inside that outer loop will be an inner loop, which will loop as many times as it loops each time the outer loop loops.

For example, if the outer loop loops 10 times, and the inner loop loops 5 times, the outer loop will loop once, then within that loop, the inner loop will loop 5 times, then the outer loop will loop its second time, and within that loop, the inner loop will loop 5 times, and so on…

This is called nesting a loop; a loop within another loop. We can continue to nest loops within loops, but for now we’ll stick with just one lopp within a loop.

Let’s give it a try.

package main

import (
	"fmt"
)

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

playground

Here we can see for each iteration of the outer loop, the inner loop prints out 0, 1, and 2.

Let’s break this up and print i on the outer loop, and j on the inner loop. Try to do this with the output of the inner loop indented

package main

import (
	"fmt"
)

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

playground