Skip to main content

Command Palette

Search for a command to run...

Loop - Nested Loops

Updated
2 min readView as Markdown
Loop - Nested Loops
S
DevRel at StackGen | Formerly at Deepfence ,Tenable , Accurics | AWS Community Builder also Docker Community Award Winner at Dockercon2020 | CyberSecurity Innovator of Year 2023 award by Bsides Bangalore | Docker/HashiCorp Meetup Organiser Bangalore & Co-Author of Learn Lightweight Kubernetes with k3s (2019) , Packt Publication & also run Non Profit CloudNativeFolks / CloudSecCorner Community To Empower Free Education reach out me twitterhttps://twitter.com/sangamtwts or just follow on GitHub -> https://github.com/sangam14 for Valuable Resources

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

18 views

GopherLabs

Part 1 of 50

Ultimate Series of Blogs for All Golang Developer

More from this blog

C

CloudNativeFolks Community

140 posts

CloudNativeFolks is non profit community that empower and educate about cloud native technology !