golang can repeat a code block with a for loop. All for loops have a condition, this can be the amount of times or a list.

You need loops to repeat code: instead of repeating the instructions over and over, simply tell golang to do it n times.

For loops in golang

Example

The program below is an example of a for loop in golang. The for loop is used to repeat the code block. golang will jump out of the code block once the condition is true, but it won’t end the program.

The code block can contain anything, from statements to function calls.

1
2
3
4
5
6
7
8
9
package main

import "fmt"

func main() {
for x := 0; x < 4; x++ {
fmt.Printf("iteration x: %d", x)
}
}

The code block can be as many lines as you want, in this example its just one line of code that gets repeated.

golang runs the code block only n times. The number of repetitions is called iterations and every round is called an iteration.

Video

Video tutorial below

Exercises

  1. Can for loops exist inside for loops?
  2. Make a program that counts from 1 to 10.