0
0
Goprogramming~5 mins

Nested loops in Go

Choose your learning style9 modes available
Introduction
Nested loops help you repeat actions inside other repeated actions, like checking every seat in a theater row by row.
When you want to print a grid or table of values.
When you need to compare every item in one list with every item in another list.
When you want to create patterns with rows and columns.
When you process multi-dimensional data like a chessboard or calendar.
Syntax
Go
for outerVariable := start; outerVariable < end; outerVariable++ {
    for innerVariable := start; innerVariable < end; innerVariable++ {
        // code to repeat
    }
}
The outer loop runs first, then the inner loop runs completely for each outer loop step.
You can use any loop variable names and conditions as needed.
Examples
Prints pairs of numbers where i goes from 1 to 3 and j goes from 1 to 2 for each i.
Go
for i := 1; i <= 3; i++ {
    for j := 1; j <= 2; j++ {
        fmt.Println(i, j)
    }
}
Prints a 2 by 3 grid of coordinates.
Go
for row := 1; row <= 2; row++ {
    for col := 1; col <= 3; col++ {
        fmt.Printf("%d,%d ", row, col)
    }
    fmt.Println()
}
Sample Program
This program prints numbers 1 to 3 in three rows, showing how nested loops create rows and columns.
Go
package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            fmt.Printf("%d ", j)
        }
        fmt.Println()
    }
}
OutputSuccess
Important Notes
Remember to indent inner loops to keep your code clear.
Too many nested loops can make your program slow, so use them wisely.
You can nest more than two loops if needed, but keep it simple for beginners.
Summary
Nested loops run one loop inside another to repeat actions multiple times.
They are useful for working with grids, tables, and multi-step tasks.
In Go, use the for loop inside another for loop with clear variable names.