Go by Example : For

The for loop in Go is used to execute a block of code repeatedly until a condition is met. There are three forms of the for loop in Go: the traditional for loop, the for loop with a single condition, and the for loop without a condition.

Traditional For Loop

The traditional for loop in Go is similar to the for loop in other programming languages. It has three components: an initializer, a condition, and a post-operation. Here’s an example:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        fmt.Println(i)
    }
}

In this example, the for loop initializes i to 0, checks if i is less than 10, and increments i by 1 after each iteration.

For Loop with Single Condition

The for loop with a single condition is similar to a while loop in other programming languages. It has only a condition and is executed repeatedly until the condition is met. Here’s an example:

package main

import "fmt"

func main() {
    i := 0
    for i < 10 {
        fmt.Println(i)
        i++
    }
}

In this example, the for loop checks if i is less than 10, and increments i by 1 after each iteration.

For Loop without a Condition

The for loop without a condition is an infinite loop. It is executed repeatedly until a break statement is encountered. Here’s an example:

package main

import "fmt"

func main() {
    i := 0
    for {
        fmt.Println(i)
        i++
        if i == 10 {
            break
        }
    }
}

In this example, the for loop prints the value of i and increments i by 1 after each iteration. The if statement checks if i is equal to 10, and if it is, the break statement is executed to break out of the loop.

In this tutorial, we’ve covered the three forms of the for loop in Go: the traditional for loop, the for loop with a single condition, and the for loop without a condition. The for loop is a powerful tool for repeating a block of code in Go.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *