Skip to content
Theory · Loops · lesson 1 of 8

The for loop

What you'll learn

What you'll learn:

  • repeat code with a for loop in three forms: three-part, condition-only and with no condition;
  • leave a loop with break and skip a pass with continue;
  • repeat an action n times with for i := range n.
A running track: the start i := 1, a checkpoint arch i <= 100 before each lap and a mark i++ in the notebook after it

The line 1 + 2 + … + 100 adds up the numbers from 1 to 100, but you would have to type all hundred terms by hand. Repeated actions call for a loop, a construct that runs code again and again while a condition is true.

Picture a runner at a stadium. The coach says, "Keep running laps until you've done a hundred." Before each new lap the runner passes a checkpoint arch, which checks the count. Then comes the lap and a mark in a notebook. A loop works the same way. Go has a single keyword for loops, for:

GO
package main

import "fmt"

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

Three forms of for

Go has no separate while keyword. Interviewers often ask which loops Go has, and this is the answer they expect: there is one keyword, for, and every other kind of loop is written with it. for has three forms, and each fits its own task.

The three-part form

The header of the loop in the example has three parts separated by semicolons:

  • the initialization i := 1 runs once, before the loop starts: the runner steps up to the start line;
  • the condition i <= 100 is checked before every pass: the checkpoint arch before the lap;
  • the post statement i++ runs after the body: the mark in the notebook.

One pass through the body is called an iteration. Let's walk through the program line by line:

  1. s := 0 sets up the sum.
  2. for i := 1; i <= 100; i++ repeats the body until i becomes 101.
  3. s += i means the same as s = s + i: the next i is added to the sum.
  4. fmt.Println(s) runs after the loop and prints 5050.

The condition sets the number of iterations. With the condition i < 5, the body runs for 1, 2, 3 and 4, and when i equals 5, the condition is already false. The variable i is declared in the header, so it is visible only inside the loop.

The widget runs the same loop with the condition i <= 3: press "Next step" and watch when each part of the header runs.

LiveThe order of the for partsstep 1 of 13 · frames: 1

s := 0 sets up the sum.

A frame is where the variables of one call live

There are no parentheses around the header, and the braces around the body are required, as in if. You use this form when you know in advance where to count from and to.

Here the stadium picture is inexact. A runner runs at least one lap, while a for loop checks its condition before the very first pass. If the condition is false from the start, the body never runs.

Condition only

A loop with only a condition has no initialization, no post statement and no semicolons: this is how Go writes a while loop. The variable is declared before the loop and changed in the body. This counts how many times 100 must be divided by 2 with integer division to leave 1:

GO
n := 100
steps := 0
for n > 1 {
    n = n / 2
    steps++
}
fmt.Println(steps) // 6

The values of n go 100, 50, 25, 12, 6, 3, 1. That is six divisions, and at 1 the condition n > 1 becomes false.

You use this form when the number of repetitions is not known in advance and depends on what happens in the body.

No condition

Drop the condition too, and you get an infinite loop, for { … }. It repeats until a return stops it. This function finds the first number whose square is greater than limit:

GO
func firstSquareOver(limit int) int {
    n := 1
    for {
        if n*n > limit {
            return n
        }
        n++
    }
}

Let's see how it works:

  1. n := 1: the search starts at one.
  2. for { repeats the body with no check at all.
  3. if n*n > limit: as soon as the square exceeds limit, return n ends both the loop and the function.
  4. n++ moves on to the next number.

For example, with limit equal to 10 the function returns 4: 3*3 is 9, while 4*4 is already 16. The trap of this form is the exit: if the condition inside never becomes true, the loop never ends.

Common mistake

The variable in a condition-only loop is never changed:

GO
i := 1
for i <= 3 { // ✗
    fmt.Println(i)
}

The body never changes i, so the condition i <= 3 is always true, and the program prints 1 forever. The runner forgot to make marks and runs on endlessly. In the course exercises, such a program is stopped by the time limit. Add i++ at the end of the body, and the loop prints 1, 2 and 3.

Key points

  • Go has one loop keyword, for; there is no separate while.
  • The initialization runs once, the condition before every iteration, the post statement after the body.
  • A condition-only loop is written as for n > 1 { … }, and an infinite one as for { … }.
  • The variable in the condition must change in the body, or the loop never ends.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way