Skip to content
AgileLogics
6 min read

Loops: Go's Only Loop, for

Prerequisites: Switch

Go has exactly one loop keyword: for. It covers every kind of loop other languages split into for, while, and do/while.

Syntax

for i := 0; i < 5; i++ { }   // classic three-part loop
for condition { }            // "while" loop
for { }                      // infinite loop (exit with break)
for i := range 5 { }         // i = 0..4 (Go 1.22+)
for i, v := range items { }  // index and value of a slice/array
  • break exits the loop immediately.
  • continue skips to the next iteration.
  • Use _ for a range value you don't need: for _, v := range items.

Example

package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        fmt.Println("classic", i)
    }

    n := 1
    for n < 100 {
        n *= 2
    }
    fmt.Println("while-style:", n)

    count := 0
    for {
        count++
        if count == 3 {
            break
        }
    }
    fmt.Println("infinite loop stopped at", count)

    for i := range 3 {
        fmt.Println("range int", i)
    }

    fruits := []string{"apple", "banana", "cherry"}
    for i, fruit := range fruits {
        fmt.Println(i, fruit)
    }

    for _, r := range "Go!" {
        fmt.Print("[", string(r), "]")
    }
    fmt.Println()

    for i := 1; i <= 6; i++ {
        if i%2 == 0 {
            continue
        }
        fmt.Print(i, ";")
    }
    fmt.Println()
}

Expected output

classic 0
classic 1
classic 2
while-style: 128
infinite loop stopped at 3
range int 0
range int 1
range int 2
0 apple
1 banana
2 cherry
[G][o][!]
1;3;5;

[]string{...} is a slice — a list of values. Slices get their own lesson shortly; for now it's enough to know that range visits each element in order.

Common mistakes

  • Wrapping the loop header in parentheses (for (i := 0; ...)) — not valid Go.
  • Writing for i := range items when you want the values: with one variable, range over a slice gives the index. Use for _, v := range items.
  • Forgetting to change the condition inside a while-style loop, creating an accidental infinite loop.

Practice

Print the sum of the numbers from 1 to 100, then print only the multiples of 3 between 1 and 15 (one per line), using continue.

Show solution
package main

import "fmt"

func main() {
    sum := 0
    for i := 1; i <= 100; i++ {
        sum += i
    }
    fmt.Println(sum) // 5050

    for i := range 16 {
        if i == 0 || i%3 != 0 {
            continue
        }
        fmt.Println(i) // 3, 6, 9, 12, 15 (one per line)
    }
}