Go For Loop

A loop repeats a block of code multiple times. Go has only one looping keyword — for. Despite having just one keyword, Go's for loop covers every looping pattern found in other languages.

Basic For Loop (Three-Part Loop)

The classic loop has three parts: initialization, condition, and post statement.

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
    }
}

Output:

1
2
3
4
5

Three-Part Loop Diagram

for  i := 1  ;  i <= 5  ;  i++  {
      │            │          │
      │            │          └── post: runs after each iteration
      │            └─────────────── condition: checked before each run
      └──────────────────────────── init: runs once at the start
}

Loop as a While Loop

Drop the init and post parts to make the for loop behave like a while loop from other languages.

package main

import "fmt"

func main() {
    count := 1

    for count <= 3 {
        fmt.Println("Count:", count)
        count++
    }
}

Output:

Count: 1
Count: 2
Count: 3

Infinite Loop

A for loop with no condition runs forever. Use break to stop it.

package main

import "fmt"

func main() {
    n := 0

    for {
        fmt.Println(n)
        n++
        if n == 3 {
            break
        }
    }
}

Output:

0
1
2

Nested For Loops

A loop inside a loop creates a grid-like repetition pattern.

package main

import "fmt"

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

Output:

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

Key Points

  • Go has only one looping keyword: for
  • The three-part form: init, condition, and post covers the standard counted loop
  • Dropping init and post makes it a while-style loop
  • An empty for { } runs infinitely — always include a break condition

Leave a Comment