Skip to content
Codewilds

Lesson 7 of 38 · Fundamentals

Go for Loops: The Only Loop You Need

medium20 XP4 min readFree lesson

Repeating work is what computers do best: adding up gold, checking every letter of a password, running a game loop until the player quits. Many languages offer for, while and do-while for this.

Go has exactly one loop keyword — for — and it covers all of those jobs. In this lesson you will learn each form and when to use it.

The classic for loop

package main

import "fmt"

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

The header has three parts separated by semicolons: the init statement runs once before the loop starts, the condition is checked before every iteration, and the post statement runs after every iteration. Just like if, there are no parentheses but the braces are required. The variable i exists only inside the loop.

for as a while loop

Leave out the init and post statements, and for keeps looping as long as its condition is true — this is Go's while:

hp := 10
for hp > 0 {
	hp -= 4
}
fmt.Println(hp) // -2

Infinite loops, break and continue

A for without any condition loops forever — until a break exits it. continue skips the rest of the current iteration and jumps straight to the next one:

package main

import "fmt"

func main() {
	n := 0
	for {
		n++
		if n%2 == 0 {
			continue // skip even numbers
		}
		if n > 7 {
			break
		}
		fmt.Print(n, " ")
	}
	fmt.Println()
}
1 3 5 7

range over an integer

Since Go 1.22, range over an integer n counts from 0 up to n-1 — the shortest way to repeat something n times:

for i := range 3 {
	fmt.Println(i) // 0, then 1, then 2
}

range over a string

range over a string walks through its characters. Each iteration gives you the byte index where the character starts and the character itself as a rune — Go's type for a single Unicode character:

package main

import "fmt"

func main() {
	for i, r := range "olé!" {
		fmt.Println(i, string(r))
	}
}
0 o
1 l
2 é
4 !

The index jumps from 2 to 4 because é takes two bytes. That is why you should use range to process text character by character: indexing with s[i] gives you single bytes and tears characters like é apart. Rune literals use single quotes, so you can write checks like r == 'é' or r >= 'a' && r <= 'z'.

When you don't need the index, ignore it with the blank identifier _: for _, r := range s. An unused i would be a "declared and not used" error.

Nested loops and labels

A loop can contain another loop. The inner loop runs completely for every iteration of the outer one:

for row := 1; row <= 3; row++ {
	line := ""
	for col := 1; col <= row; col++ {
		line += "*"
	}
	fmt.Println(line)
}
*
**
***

break and continue only affect the innermost loop. To leave an outer loop from inside an inner one, put a label before the outer loop and name it: break grid (or continue grid):

package main

import "fmt"

func main() {
grid:
	for row := range 3 {
		for col := range 3 {
			if row*col == 2 {
				fmt.Println("found at", row, col)
				break grid
			}
		}
	}
}
found at 1 2

Common mistakes

  • Off-by-one errors: i < n and i <= n differ by one iteration. Check the first and last values of your loop variable.
  • Never-ending loops: a while-style loop must change something its condition depends on. (Here the runtime stops a program that runs too long.)
  • break inside a switch: it leaves only the switch, not the surrounding for. Use a label or return.
  • Looping over bytes instead of runes: for i := 0; i < len(s); i++ with s[i] treats é as two separate bytes.

Assignment

The function skeletons are given — put your code where the TODO comments are and use return to hand back the result.

  1. SumTo(n int) int returns the sum 1 + 2 + … + n. SumTo(5) is 15. For n less than 1 it returns 0.
  2. Factorial(n int) int returns n! = 1 × 2 × … × n. Factorial(5) is 120, and Factorial(0) is 1. n is never negative.
  3. CountVowels(s string) int counts the vowels a, e, i, o and u in s, in lower or upper case. CountVowels("Gopher") is 2.
  4. CollatzSteps(n int) int counts how many steps the Collatz sequence needs to get from n down to 1. In each step, an even n becomes n / 2 and an odd n becomes 3*n + 1. CollatzSteps(6) is 8 (6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1) and CollatzSteps(1) is 0. n is always at least 1.

Loops in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Press Run to execute your code, or Submit to check it against the tests.