Lesson 4
Mastering Nested Loops in Go
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).

Go
1for initialization; condition; iteration { 2 // outer loop code 3 for initialization; condition; iteration { 4 // inner loop code 5 } 6}

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:

Go
1for i := 0; i < 5; i++ { 2 for j := 0; j <= i; j++ { 3 fmt.Print("* ") // print "* " 4 } 5 fmt.Println() // move to the next line 6} 7// Prints: 8// * 9// * * 10// * * * 11// * * * * 12// * * * * *

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.

Go
1i := 5 2for i > 0 { 3 j := i 4 for j > 0 { 5 fmt.Print(j, " ") // print the number 6 j-- 7 } 8 fmt.Println() // move to the next line 9 i-- 10} 11// Prints: 12// 5 4 3 2 1 13// 4 3 2 1 14// 3 2 1 15// 2 1 16// 1

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

Advanced Tasks with Nested Loops

Nested loops are particularly effective for tasks such as traversing multi-dimensional arrays and executing complex searches.

Given a 2D slice, let's print all elements using nested loops:

Go
1intArray := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} 2 3for i := 0; i < len(intArray); i++ { // iterates over rows 4 for j := 0; j < len(intArray[i]); j++ { // iterates over columns 5 fmt.Print(intArray[i][j], " ") // prints each element 6 } 7 fmt.Println() // moves to the next line 8} 9// Prints: 10// 1 2 3 11// 4 5 6 12// 7 8 9

To search for an integer in a 2D slice, nested loops again come in handy. Here's a demonstration that searches for the number 7:

Go
1intArray := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} 2searchNumber := 7 3isFound := false 4 5for i := 0; i < len(intArray); i++ { // iterates over rows 6 for j := 0; j < len(intArray[i]); j++ { // iterates over columns 7 if intArray[i][j] == searchNumber { 8 fmt.Println("Number", searchNumber, "found at [", i, ", ", j, "]") 9 isFound = true 10 } 11 } 12} 13 14if !isFound { 15 fmt.Println("Number", searchNumber, "not found in the array.") 16} 17// Prints: Number 7 found at [ 2 , 0 ]

Upon running the code, our nested loops locate and identify the number 7 in the third row.

Quick Nested Loops Tips and Warnings

Even though nested loops are incredibly useful, be cautious to avoid pitfalls such as infinite loops. A loop will turn into an infinite one if it isn't designed carefully to eventually terminate. Remember, proper controls and conditional statements are crucial.

Lesson Summary and Practice

Well done! You now understand the concept of nested loops and can effectively use for loops in Go. Shortly, you'll commence work on practice exercises to deepen your understanding of loops in Go. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.