Go - Loops



There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

Loop in Go Language

A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −

Loop Architecture

Type of Go Loops

Go programming language provides the following types of loop to handle looping requirements.

Sr.No Loop Type & Description
1 for loop

It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

2 nested loops

These are one or multiple loops inside any for loop.

1. Go for Loop

A for loop is a repetition control structure. It allows you to write a loop that needs to execute a specific number of times.

Example

The following example demonstrates a for loop in Go:

package main
import "fmt"

func main() {
    // Print numbers from 1 to 10
    for i := 1; i <= 10; i++ {
        fmt.Println(i)
    }
}

When you compile and execute the above program, it produces the following result −

1
2
3
4
5
6
7
8
9
10

2. Go Nested for Loop

Go language allows nesting of loops where you can use one or more loops inside a loop. The main loop is known as the outer loop, while the loop(s) placed inside it are known as the inner loop(s).

Example

The following example demonstrates the use of nested for loops in Go:

package main
import "fmt"

func main() {
    // Outer loop
    for i := 1; i <= 5; i++ {
        // Inner loop
        for j := 1; j <= i; j++ {
            fmt.Print("*")
        }
        fmt.Println() // prints a new line
    }
}

When you compile and execute the above program, it produces the following result −

*
**
***
****
*****

Go Loop Control Statements

Loop control statements change an execution from its normal sequence. When an execution leaves its scope, all automatic objects that were created in that scope are destroyed.

Go supports the following control statements −

Sr.No Control Statement & Description
1 break statement

It terminates a for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.

2 continue statement

It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3 goto statement

It transfers control to the labeled statement.

1. Go break Statement

Thebreak statement immediately terminates the loop, and the program control resumes at the next statement following the loop.

Example

In this example, we are running a loop from 1 to 10 and breaking it when it reaches the counter's value of 5:

package main
import "fmt"

func main() {
    // Print numbers from 1 to 10, break when value is 5
    for i := 1; i <= 10; i++ {
        if i == 5 {
            break
        }
        fmt.Println(i)
    }
}

When you compile and execute the above program, it produces the following result −

1
2
3
4

2. Go continue Statement

The continue statement sends the execution to the next iteration of the loop, skipping any code in between.

Example

In the following example, the loop will skip the current iteration when the value is 5 and continue to the next iteration:

package main
import "fmt"

func main() {
    // Print numbers from 1 to 10, continue when value is 5
    for i := 1; i <= 10; i++ {
        if i == 5 {
            continue
        }
        fmt.Println(i)
    }
}

When you compile and execute the above program, it produces the following result −

1
2
3
4
6
7
8
9
10

3. Go goto Statement

The goto statement provides an unconditional jump from the goto to a labelled statement in the same function.

Example

In the following example, we are printing numbers from 1 to 5 using the goto statement in Go:

// Print numbers from 1 to 5 using goto
package main
import "fmt"

func main() {
    // Loop counter
    i := 1
INIT:
    // Condition
    if i > 5 {
        return
    }
    fmt.Println(i)
    // counter increment
    i++
    goto INIT
}

When you compile and execute the above program, it produces the following result −

1
2
3
4
5

The Infinite Loop in Go

A loop becomes an infinite loop if its condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty or by passing true to it.

Example

The following example demonstrates the use of a nested loop in the Go language:

package main

import "fmt"

func main() {
   for true  {
       fmt.Printf("This loop will run forever.\n");
   }
}

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.

Note − You can terminate an infinite loop by pressing Ctrl + C keys.

Advertisements