ProgramGuru

Nested Loops

Start with Go Nested Loops

A nested loop places one loop inside another. For each iteration of the outer loop, the inner loop completes all of its iterations.

What you’ll learn

  • Trace two levels of iteration.
  • Predict grid output.
  • Count the total inner-loop executions.

Understand the idea

Nested loops are useful for grids, multiplication tables and comparing pairs. If the outer loop repeats m times and the inner loop repeats n times on each outer pass, the inner body runs m × n times.

Each loop typically uses its own index variable, such as row and col. Clear names help readers distinguish the dimensions of a grid.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for nested loopsThe inner loop restarts each time the outer loop advances.Start row 1Step 1Visit columns 1–3Step 2Advance row 2Step 3Visit columns 1–3Step 4The inner loop restarts each time the outer loop advances.
The inner loop restarts each time the outer loop advances.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	for row := 1; row <= 2; row++ {
		for col := 1; col <= 3; col++ {
			fmt.Printf("(%d,%d) ", row, col)
		}
		fmt.Println()
	}
}

Output

(1,1) (1,2) (1,3) 
(2,1) (2,2) (2,3) 

Trace what the program does

The outer loop takes row 1, while the inner loop prints columns 1, 2 and 3. Then the outer loop advances to row 2 and the inner loop begins at column 1 again. The grid has two rows and three columns.

Avoid common mistakes

  • Do not accidentally use the same index variable for two independent dimensions.
  • Nested loops can grow expensive for large inputs; the total work often multiplies.

Try it yourself

Change the grid to three rows and two columns. Count how many coordinate pairs are printed before running.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

How many times does the inner body execute for 2 outer iterations and 3 inner iterations each?
Choose one answer. You can try again.

Answer and explanation

6

Correct. The outer loop takes row 1, while the inner loop prints columns 1, 2 and 3.

What you should remember

You have practiced Go Nested Loops in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: range →