Introduction

Greetings! This lesson is instrumental in mastering nested loops in Go. Similar to how our daily routine might involve multiple tasks (inner loops) that we repeat for every day of the week (outer loop), nested loops in programming involve the execution of an inner loop within an outer loop. Let's kick things off!

Nested Loops: The Basics

Suppose your day involves multiple tasks like cooking and eating for each meal: breakfast, lunch, and dinner. In this case, the meals represent the outer loop, while the tasks constitute the inner loop. Similarly, in Go, we can write a for loop (inner loop) inside another for loop (outer loop).

for initialization; condition; iteration {
    // outer loop code
    for initialization; condition; iteration {
        // inner loop code
    }
}

The program evaluates the condition of the outer loop. If it's true, it enters the loop and executes the inner loop to completion before moving on to the next iteration of the outer loop.

Go Nested `for` Loops

Writing nested for loops in Go is straightforward. To demonstrate, let's print a 5x5 star pattern using nested loops:

for i := 0; i < 5; i++ {
    for j := 0; j <= i; j++ {
        fmt.Print("* ") // print "* "
    }
    fmt.Println() // move to the next line
}
// Prints:
// *
// * *
// * * *
// * * * *
// * * * * * 

In this instance, the outer loop governs the rows, while the inner loop controls the columns. The result is a diagonal pattern of stars printed in the console!

Emulating `while` Loops in Go

As Go doesn't feature a distinct while keyword, we utilize the for loop to mimic the behavior of a while loop. Nested for loops that emulate while loops function precisely like the nested for loops we covered earlier.

i := 5
for i > 0 {
    j := i
    for j > 0 {
        fmt.Print(j, " ") // print the number
        j--
    }
    fmt.Println() // move to the next line
    i--
}
// Prints:
// 5 4 3 2 1
// 4 3 2 1
// 3 2 1
// 2 1 
// 1 

Upon executing this, you'll notice five lines, each containing decreasing numbers, just as the comment explains.

Advanced Tasks with Nested Loops
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal