Loops with for

Introduction

A loop repeats a block of code. Without loops, a program that adds the numbers from 1 to 1000 would need a thousand lines; with a loop it needs three. Many languages have for, while and do-while. Go has only one keyword, for, and it can be written in three shapes. Once you know them you can repeat anything: count to a number, wait until a condition becomes false, or go through every character of a text.

How it works

The first shape is the counting loop. It has three parts: a setup that runs once, a condition that is checked before every round, and a step that runs after every round.

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

Here i starts at 1, the loop runs while i <= 5, and i++ adds one after each round. The variable i exists only inside the loop. The second shape keeps only the condition, so it works like a while loop in other languages:

for x > 1 {
	x = x / 2
}

The third shape has nothing after for and repeats forever. You leave it with break:

for {
	if done {
		break
	}
}

Two keywords control a loop from the inside. break leaves the loop at once. continue skips the rest of the current round and goes to the next one. In a counting loop, continue still runs the step.

Loops can sit inside other loops. The inner loop runs completely for every round of the outer loop, which is how you print tables and grids. Take care with the number of rounds: a loop inside a loop with 1000 rounds each runs a million times.

Finally, range goes through a string. for i, ch := range "Go" gives the position i and the character ch for every character. A character has the type rune, a number, so string(ch) turns it back into text. If you do not need the position, write _ in its place: for _, ch := range text. Lesson 7 shows how range works with slices, and lesson 8 with maps.

An endless loop that never reaches break hangs the program; on this site a run stops after 10 seconds.

Example

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)

	sum := 0
	for i := 1; i <= n; i++ {
		sum += i
	}
	fmt.Println("sum 1..n:", sum)

	x := n
	steps := 0
	for x > 1 {
		if x%2 == 0 {
			x = x / 2
		} else {
			x = 3*x + 1
		}
		steps++
	}
	fmt.Println("collatz steps:", steps)

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

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

	for i, ch := range "Go" {
		fmt.Println(i, string(ch))
	}
}

Input used: 6

Line by line

  1. for i := 1; i <= n; i++ adds the numbers from 1 to n; with n = 6 that is 21.
  2. for x > 1 is the while form. It follows the Collatz rule: halve even numbers and triple-plus-one odd numbers until 1, and steps counts the rounds.
  3. for i := 1; ; i++ has no condition, so it needs break. continue skips even numbers, and break stops after 9.
  4. The two nested loops print a 3 by 3 multiplication table; %3d makes each number 3 characters wide.
  5. range "Go" gives each character with its position.

Expected result

With this input:

6

it prints:

sum 1..n: 21
collatz steps: 8
1 3 5 7 9 
  1  2  3
  2  4  6
  3  6  9
0 G
1 o

In the real world

Loops process every record in a file, every pixel in an image and every request waiting in a queue. Servers use an endless for loop that waits for the next request. Knowing which loop shape fits saves time: a counting loop when you know how many rounds, a condition loop when you wait for something to happen, and range when you visit every item.

Common mistakes

  • Off-by-one errors, such as i < n when you needed i <= n.
  • Forgetting the step, so the condition never becomes false and the loop never ends.
  • Changing the loop variable inside the body by accident.
  • Looking for while in Go. It does not exist; use for condition.
  • Using break and expecting it to leave two loops. It leaves only the inner one.

Best practices

  • Start a counting loop at 0 when you will use the number as a position, and at 1 when you count items.
  • Prefer a loop with a clear end condition to an endless loop with a hidden break.
  • Keep loop bodies short; move long bodies into a function.

Summary

Go has one loop, for, with three shapes: the counting loop, the condition-only loop and the endless loop. break leaves a loop and continue starts the next round. Loops nest, and range visits each character of a string with its position.

Quick check

1. Which keyword makes a while loop in Go?
2. How many times does for i := 0; i < 4; i++ run its body?
3. What does continue do?
4. How do you leave an endless for loop?
5. What does range give for each item of a string?

Key takeaways

  • Go has one loop keyword, for, which covers counting loops, while loops and endless loops.
  • break leaves the loop and continue jumps to the next round.
  • for i, ch := range text visits each character with its position.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.