Hi, I’m @Luo Zhu

This article was first published on luo Zhu’s official website

This article was translated from Golang Tutorial Series

This article synchronizes in the public account Luo Zhu early teahouse, reprint please contact the author.

Loop statements are used to execute blocks of code repeatedly.

For is the only loop available in Go. Go does not have the while or do while loop that exists in other languages (such as C).

For loop syntax

for initialisation; condition; post {
}
Copy the code

The initialization statement will be executed only once. After the loop is initialized, the condition is checked. If the condition evaluates to true, the body of the loop inside {} is executed, followed by the POST statement. After each successful iteration of the loop, the POST statement is executed. After the POST statement is executed, the condition is rechecked. If true, the loop continues, otherwise the for loop terminates.

The three parts of the for loop in Go, initialization, condition, and publication, are optional. Let’s look at an example to better understand loops.

The sample

Let’s write a program that prints all numbers from 1 to 10 using a for loop.

package main

import (
    "fmt"
)

func main(a) {
    for i := 1; i <= 10; i++ {
        fmt.Printf(" %d",i)
    }
}
Copy the code

Run in playground

In the above program, I is initialized to 1. The conditional statement checks for I <= 10. If the condition is true, the value of I is printed, otherwise the loop terminates. At the end of each iteration, the POST statement increments I by 1. Once I is greater than 10, the loop terminates.

The above program will print 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Variables declared in a for loop are only available within the scope of the loop. Therefore, there is no loop access to I outside of the principal.

break

The break statement is used to abruptly terminate the for loop before completing normal execution and to shift control to the line of code following the for loop.

Let’s write a program that prints numbers from 1 to 5 using break.

package main

import (
    "fmt"
)

func main(a) {
    for i := 1; i <= 10; i++ {
        if i > 5 {
            break // If I is greater than 5, the loop terminates
        }
        fmt.Printf("%d ", i)
    }
    fmt.Printf("\nline after for loop")}Copy the code

Run in playground

In the above program, the I value is checked during each iteration. If I is greater than 5, break is executed and the loop is terminated. The print statement is then executed after the for loop. The above program will print:

1 2 3 4 5
line after for loop
Copy the code

continue

The continue statement is used to skip the current iteration of the for loop. Any code that exists in the for loop after the continue statement will not be executed for the current iteration. The loop continues to the next iteration.

Let’s write a program that prints all odd numbers from 1 to 10 using continue.

package main

import (
    "fmt"
)

func main(a) {
    for i := 1; i <= 10; i++ {
        if i%2= =0 {
            continue
        }
        fmt.Printf("%d ", i)
    }
}
Copy the code

Run in playground

In the program above, line if I % 2 == 0 checks if the prompt to divide I by 2 is 0. If zero, the number is even, the continue statement is executed, and control moves to the next iteration of the loop. Therefore, the print statement after continue will not be called, and the loop will proceed to the next iteration. The output of the above program is 1, 3, 5, 7, 9.

Nested loop

A for loop with another for loop inside it is called a nested for loop. Let’s learn about nested for loops by writing a program that prints the following sequence.

*
**
***
****
*****
Copy the code

The following program uses nested for loops to print sequences. The variable n in line 8 stores the number of lines in the sequence. In our case, it’s 5. The outer for loop iterates I from 0 to 4, and the inner for loop iterates j from 0 to the current value of I. The inner loop prints “*” for each iteration, while the outer loop prints a new line at the end of each iteration. Run the program and you will see the sequence printed as output.

package main

import (
    "fmt"
)

func main(a) {
    n := 5
    for i := 0; i < n; i++ {
        for j := 0; j <= i; j++ {
            fmt.Print("*")
        }
        fmt.Println()
    }
}
Copy the code

Run in playground

The label

The tag can be used to interrupt the outer loop from the inner for loop. Let’s take a simple example to see what I mean.

package main

import (
    "fmt"
)

func main(a) {
    for i := 0; i < 3; i++ {
        for j := 1; j < 4; j++ {
            fmt.Printf("i = %d , j = %d\n", i, j)
        }

    }
}
Copy the code

Run in playground

The above program is self-explanatory, it will print:

i = 0 , j = 1
i = 0 , j = 2
i = 0 , j = 3
i = 1 , j = 1
i = 1 , j = 2
i = 1 , j = 3
i = 2 , j = 1
i = 2 , j = 2
i = 2 , j = 3
Copy the code

There’s nothing special about it!

What if we want to stop printing when I and j are equal. To do this, we need to exit the external for loop. Adding a break to the inner for loop only exits the inner for loop when I and j are equal.

package main

import (
    "fmt"
)

func main(a) {
    for i := 0; i < 3; i++ {
        for j := 1; j < 4; j++ {
            fmt.Printf("i = %d , j = %d\n", i, j)
            if i == j {
                break}}}}Copy the code

Run in playground

In the above program, I added a break to the inner for loop when I and j on line 10 were equal. This simply exits the inner for loop, and the outer loop continues execution. The program will print:

i = 0 , j = 1
i = 0 , j = 2
i = 0 , j = 3
i = 1 , j = 1
i = 2 , j = 1
i = 2 , j = 2
Copy the code

This is not the expected output. When I and j are equal, when they’re equal to 1, we need to stop printing. The tag can be used to interrupt open from the external loop. Let’s rewrite the above program using the tag:

package main

import (
    "fmt"
)

func main(a) {
outer:
    for i := 0; i < 3; i++ {
        for j := 1; j < 4; j++ {
            fmt.Printf("i = %d , j = %d\n", i, j)
            if i == j {
                break outer
            }
        }

    }
}
Copy the code

Run in playground

In the above program, we added the tag outer to the outer for loop at line 8, and broke the outer for loop by specifying the tag at line 13. When I and j are equal, the program will stop printing. This program will output:

i = 0 , j = 1
i = 0 , j = 2
i = 0 , j = 3
i = 1 , j = 1
Copy the code

More examples

Let’s write more code to cover all the variations of the for loop. The following program prints all even numbers from 0 to 10.

package main

import (
    "fmt"
)

func main(a) {
    i := 0
    for; i <=10; { // initialisation and post is omitted
        fmt.Printf("%d ", i)
        i += 2}}Copy the code

Run in playground

We already know that all three parts of the for loop, initialisation, condition and post are optional. Initialisation and post are omitted from the above procedure. Outside of the for loop, I is initialized to 0. As long as I <= 10, the loop executes. I added 2 to the for loop. The above program outputs 0, 2, 4, 6, 8, 10.

You can also omit the semicolon in the for loop of the above program. You can think of this format as an alternative to the while loop. The above program can be rewritten as:

package main

import (
    "fmt"
)

func main(a) {
    i := 0
    for i <= 10 { // The semicolon is omitted, leaving only the conditional statement
        fmt.Printf("%d ", i)
        i += 2}}Copy the code

Run in playground

Multiple variables can be declared and manipulated in a for loop. Let’s write a program that prints the following sequence using multiple variable declarations.

10 * 1 = 10 11 * 2 = 22 12 * 3 = 36 13 * 4 = 52 14 * 5 = 70 15 * 6 = 90 16 * 7 = 112 17 * 8 = 136 18 * 9 = 162 19 * 10 =  190Copy the code
package main

import (
    "fmt"
)

func main(a) {
    for no, i := 10.1; i <= 10 && no <= 19; i, no = i+1, no+1 {
        fmt.Printf("%d * %d = %d\n", no, i, no*i)
    }
}
Copy the code

Run in playground

In the above program, no and I are declared and initialized to 10 and 1, respectively. At the end of each iteration, they increase by 1. The Boolean operator && is used to ensure that I is less than or equal to 10 and no is less than or equal to 19.

An infinite loop

The syntax for creating an infinite loop is:

for{}Copy the code

The following program will continue to print Hello World without terminating.

package main

import "fmt"

func main(a) {
    for {
        fmt.Println("Hello World")}}Copy the code

If you try to run the above program in Go Park, you receive the error message Process Took too long. Try running it on your local system to print Hello World indefinitely.

There is also a range that can be used for array operations in a for loop. We’ll cover arrays when we learn about them in a later tutorial.