GoLang - For Loop

4 minute read

In this tutorial, you will learn about “for Loop in Go Programming” with the help of example.

In Go programming, the “for” loop is a powerful construct that allows you to repeatedly execute a block of code based on a specified condition. It is a fundamental control structure that enables you to iterate over collections, perform repetitive tasks, and control program flow. In this tutorial, we will explore the basics of the “for” loop in Go programming with examples and explanations in simple and easy-to-understand language. So let’s dive in and learn about the “for” loop in Go!

Syntax:

The general syntax of the “for” loop in Go is as follows:

for initialization; condition; increment {
    // code to be executed repeatedly
}

Simple for Loop

The simplest form of the “for” loop executes a block of code repeatedly as long as a specified condition is true.

Example:

package main

import "fmt"

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

In the example above, we have a “for” loop that starts with 'i' initialized to 1. The loop continues as long as 'i' is less than or equal to 5. In each iteration, it prints the value of 'i' using the 'fmt.Println' statement. After each iteration, the increment statement 'i++' increases the value of 'i' by 1.

Infinite Loop

You can create an infinite loop by omitting the initialization, condition, and increment statements in the “for” loop.

Example:

package main

import "fmt"

func main() {
    for {
        fmt.Println("This is an infinite loop")
    }
}

In this example, the “for” loop does not have any initialization, condition, or increment statement. Therefore, it creates an infinite loop that continuously prints “This is an infinite loop” to the console. Be cautious when using infinite loops and ensure you have a proper way to terminate them.

Range-based for Loop

The “for” loop can be used with the 'range' keyword to iterate over elements in a collection, such as an array, slice, or map.

Example:

package main

import "fmt"

func main() {
    nums := []int{1, 2, 3, 4, 5}

    for index, value := range nums {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

In this example, we have a slice of integers 'nums' containing five elements. The “for” loop with the 'range' keyword iterates over each element in 'nums'. In each iteration, it assigns the 'index' and 'value' of the current element to the variables index and value, respectively. It then prints the index and value using the 'fmt.Printf' statement.

Nested for Loops

You can nest one or more “for” loops within another “for” loop to create complex iterative patterns.

Example:

package main

import "fmt"

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

In this example, we have two nested “for” loops. The outer loop iterates from 1 to 3, and the inner loop also iterates from 1 to 3. In each iteration of the inner loop, it prints the values of 'i' and 'j' using the 'fmt.Printf' statement. This creates a pattern where each value of 'i' is paired with each value of 'j', resulting in nine combinations printed to the console.

Skipping Iterations with continue

You can use the continue statement within a loop to skip the remaining code in the current iteration and move to the next iteration.

Example:

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 3 {
            continue
        }
        fmt.Println(i)
    }
}

In this example, the “for” loop iterates from 1 to 5. However, when i is equal to 3, the continue statement is executed, which skips the remaining code in that iteration. As a result, the number 3 is not printed, and the loop continues to the next iteration.

Remember to pay attention to the syntax of the “for” loop and ensure that you have a termination condition to prevent infinite loops. Experiment with different variations of the “for” loop and explore its versatility in your Go programs.

Conclusion

The “for” loop is a vital construct in Go programming that allows you to repeat a block of code based on a specified condition. In this tutorial, we explored the basics of using the “for” loop in Go with simple and easy-to-understand examples. We learned how to create a simple “for” loop with an initialization, condition, and increment statement, as well as how to create infinite loops and range-based loops.

Additionally, we discovered how to use nested “for” loops to create complex iterative patterns and how to skip iterations using the continue statement. By mastering the “for” loop, you can perform repetitive tasks, iterate over collections, and control the flow of your Go programs!

Congratulations on completing this beginner’s guide to the “for” loop in Go programming! With this knowledge, you’re now equipped to perform iterative tasks and control program flow in your Go programs. So go ahead, practice using the “for” loop, and unlock the full potential of repetitive tasks in your code!

Updated: