๐ŸŽ“ A1Learner
๐Ÿ”

Go For Loop

A for loop is a loop that repeats a block of code. One for header can hold the start, the condition, and the change for a counter.

Counting with three parts

The counter starts at 1 and grows by 1 each pass. The loop stops after printing 3.

package main

import "fmt"

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

A condition only loop

This header holds only a condition. The counter changes inside the block instead.

package main

import "fmt"

func main() {
	i := 3
	for i >= 1 {
		fmt.Println(i)
		i--
	}
}

Stepping by two

The change part adds 2 after each pass. The counter prints the even numbers up to 8.

package main

import "fmt"

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

Nested loops build rows

The inner loop prints three stars with no new line. The print after it ends the row.

package main

import "fmt"

func main() {
	for row := 1; row <= 2; row++ {
		for col := 1; col <= 3; col++ {
			fmt.Print("*")
		}
		fmt.Println()
	}
}

Example

package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		fmt.Println("7 x", i, "=", (7 * i))
	}
}

Key points

  • The classic header holds three parts split by semicolons.
  • The first part sets the starting value of the counter.
  • The second part is the condition checked before each pass.
  • The third part changes the counter after each pass.
  • A for loop with only a condition leaves out the start and change parts.
  • A nested loop is a loop inside a loop, and the inner loop runs fully on each outer pass.

In this example, i starts at 1. The first pass prints "7 x 1 = 7". The second pass prints "7 x 2 = 14". The third pass prints "7 x 3 = 21". The condition then fails and the loop stops.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

Which part of a classic for header runs after each pass?