← Back to Go Course | Chapter 3: Control Flow | Lesson 1 of 7

The for Loop

The for loop is Go's way of saying 'do this again and again until I tell you to stop' -- and it's the only kind of loop Go has.

The Classic Three-Part for Loop

Go's most familiar for loop has three parts separated by semicolons: an initializer, a condition checked before each iteration, and a post statement run after each iteration. This mirrors the classic C-style for loop found in many languages.

Example: The Classic Three-Part for Loop

markup
package main

import "fmt"

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

for as a while Loop

Dropping the init and post clauses and keeping only a condition turns for into the equivalent of a while loop found in other languages -- it keeps running as long as the condition stays true.

Example: for as a while Loop

markup
package main

import "fmt"

func main() {
	n := 1
	for n < 100 {
		n *= 2
	}
	fmt.Println("first power of two >= 100:", n)
}

Infinite Loops

Omitting all three clauses produces an infinite loop, 'for { }', which runs forever unless something inside it breaks out or returns from the function. This form is often used for servers or workers that should run until explicitly stopped.

Note: Always pair an infinite for loop with a break, return, or os.Exit so the program has a way out.

Example: Infinite Loops

markup
package main

import "fmt"

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

Nested for Loops

Because for is Go's only loop construct, nested loops (a loop inside a loop) are written by simply placing one for statement inside another, commonly used for iterating over grids or combinations of two sequences.

Example: Nested for Loops

markup
package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		for j := 1; j <= 2; j++ {
			fmt.Printf("(%d,%d) ", i, j)
		}
	}
	fmt.Println()
}
Common Mistakes
  1. Looking for a while or do-while keyword -- Go only has for, which can be written in while-style with just a condition.
  2. Forgetting the loop variable is scoped to the loop and modifying it inside expecting it to persist meaningfully after the loop ends.
  3. Writing an infinite 'for {}' without a break condition or return, accidentally hanging the program.
Chapter Summary
  • Go has exactly one looping keyword, for, used in several styles.
  • The classic three-part form is 'for init; condition; post { }'.
  • 'for condition { }' behaves like a while loop in other languages.
  • 'for { }' with no clauses loops forever until an explicit break or return.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.