Menu
Coddy logo textTech

Nested Loops

Part of the Fundamentals section of Coddy's GO journey — lesson 49 of 109.

Nested Loops are loops placed inside another loop. The inner loop runs completely for each iteration of the outer loop.

Let's create a multiplication table for numbers 1-3 using nested loops:

for i := 1; i <= 3; i++ {
    for j := 1; j <= 3; j++ {
        fmt.Printf("%d×%d=%d\t", i, j, i*j)
    }
    fmt.Println()
}

After executing this code, we get a multiplication table where each row represents one value of the outer loop variable (i) multiplied by all values of the inner loop variable (j). The output will show on the screen:

1×1=1   1×2=2   1×3=3   
2×1=2   2×2=4   2×3=6   
3×1=3   3×2=6   3×3=9   

Let's understand how this works step by step:

First, the outer loop sets i=1 and the inner loop runs completely:

i=1, j=1: prints "1×1=1"
i=1, j=2: prints "1×2=2"
i=1, j=3: prints "1×3=3"

After the inner loop finishes, we print a new line with fmt.Println().

Then the outer loop sets i=2 and the inner loop runs again:

i=2, j=1: prints "2×1=2"
i=2, j=2: prints "2×2=4"
i=2, j=3: prints "2×3=6"

Finally, the outer loop sets i=3 and the inner loop runs one last time:

i=3, j=1: prints "3×1=3"
i=3, j=2: prints "3×2=6"
i=3, j=3: prints "3×3=9"

This pattern of loops within loops is very useful for working with tables of data or creating grid-like structures.

challenge icon

Challenge

Beginner

In this challenge, you'll practice using nested loops to print a simple pattern. The outer loop will iterate through rows, and the inner loop will iterate through columns to create a small grid of characters.

Complete the nested loops to print a 3x3 grid of asterisks (*). Each asterisk must be followed by a space, so each row should look like * * * (with a trailing space). The expected output is:

* * * 
* * * 
* * * 

Cheat sheet

Nested loops are loops placed inside another loop. The inner loop runs completely for each iteration of the outer loop.

for i := 1; i <= 3; i++ {
    for j := 1; j <= 3; j++ {
        fmt.Printf("%d×%d=%d\t", i, j, i*j)
    }
    fmt.Println()
}

The outer loop controls rows, while the inner loop controls columns. For each outer loop iteration, the inner loop completes all its iterations before moving to the next outer loop iteration.

Try it yourself

package main

import "fmt"

func main() {
	// Number of rows and columns in our grid
	rows := 3
	columns := 3
	
	// TODO: Create a nested loop to print a grid of asterisks (*)
	// The outer loop should iterate through the rows
	// The inner loop should iterate through the columns
	for i := 0; i < rows; i++ {
		// Add your inner loop here to print asterisks in each column
		
		// This prints a new line after each row
		fmt.Println()
	}
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals