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.

Related course: Introducing Go: Build Reliable, Scalable Programs

For loops in golang

Syntax

The simplest counter-based iteration, the basic form is:

1
for initialization statement; conditional statement; modified statement {}

The heads of these three sections, which are separated by a semicolon; they do not need to be enclosed in parentheses ().

You can use a counter in a loop, this counter i repeats until x >= 10.

1
for i := 0; i < 10; i++ {

In the syntax above we use i++ to increase i, but i = i + 1 is also permitted. It’s the same thing.

Example

Simple loop

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\n", x)
}
}

1
2
3
4
iteration x: 0
iteration x: 1
iteration x: 2
iteration x: 3

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.

Loop over array

An array is a set of items of the same data type. You can loop over an array too:

1
2
3
4
5
6
7
8
9
10
11
12
13
package main
import (
"fmt"
)
func main() {
// define array
a := []int{1, 2, 3, 4, 5, 6}

// loop over array
for i := 0; i < len(a); i = i +1 {
fmt.Println("character :", a[i])
}
}
1
2
3
4
5
6
character : 1
character : 2
character : 3
character : 4
character : 5
character : 6

Video

Video tutorial below

Exercises

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

Download Answers

Related course: Introducing Go: Build Reliable, Scalable Programs