Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    Go Loops

    Golang Tutorials


    A loop in Go programming is a control flow statement that allows the execution of a block of code repeatedly until a specific condition is met. Go programming language has a "for" keyword for performing loops. This keyword can be utilized to execute different types of loops, such as "for" loops, "while" loops, "infinite" loops, and "foreach" loops.

    For Loop

    The most common loop in every programming language is the "for" loop. The same goes for Golang. A "for" loop executes a block of code repeatedly until a specific condition is met.

    Syntax:

    for initialization; condition; post {
       // code to be executed
    }
    

    A "for" loop in Go has three parts: the "initialization", the "condition", and the "post" statement. The initialization statement is executed only once before the loop starts. The condition is evaluated before each iteration, and the loop will continue to execute if it is true. The post statement is executed after each iteration. Here is an example that uses a "for" loop to print the numbers 1 to 5:

    Example:

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

    Program Output:

    1
    2
    3
    4
    5

    While Loop

    A "while" loop in the Go programming language repeatedly executes a block of code as long as a given condition is true.

    Syntax:

    for condition {
       // code to be executed
    }
    

    The "condition" is a boolean expression evaluated before each loop iteration. The code block inside the loop will be executed if the condition is true. If the condition is false, the loop will be exited, and the program will continue with the following statement after the loop. Here is an example that uses a "while" loop to print the numbers 1 to 5:

    Example:

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

    Program Output:

    1
    2
    3
    4
    5

    Infinite Loop

    An infinite loop in Go is a loop that continues to execute indefinitely because the condition that controls the loop constantly evaluates to true. In Go, an infinite loop can be created using the for keyword with no condition.

    Syntax:

    for {
       // code to be executed
    }
    

    An example of an infinite loop that continuously prints "Hello, World!":

    Example:

    package main
    import "fmt"
    
    func main() {
       for {
          fmt.Println("Hello, World!")
       }
    }
    

    It's important to note that infinite loops can cause a program to hang and consume many resources if not implemented cautiously. It's best to use infinite loops with a specific exit condition or limit to prevent the program from running indefinitely.

    Range Loop

    In Go, the "for" loop can be used to iterate over a range of values or the elements of an array, slice, or map. The range keyword is used to iterate over the elements.

    Here is an example of using the "for" loop with the range keyword to iterate over the elements of an array:

    Example:

    package main
    import "fmt"
    
    func main() {
        numbers := []int{1, 2, 3, 4, 5}
        for i, number := range numbers {
            fmt.Printf("Index: %d, Number: %d\n", i, number)
        }
    }

    Program Output:

    Index: 0, Number: 1
    Index: 1, Number: 2
    Index: 2, Number: 3
    Index: 3, Number: 4
    Index: 4, Number: 5

    The "for" loop can also be used to iterate over the elements of a slice or map in a similar way:

    Example:

    package main
    import "fmt"
    
    func main() {
       // slice
       fruits := []string{"apple", "banana", "orange"}
       for i, fruit := range fruits {
         fmt.Println(i, fruit)
      }
    
      // map
      ages := map[string]int{"Alex": 25, "Bob": 30, "Charlie": 35}
      for name, age := range ages {
         fmt.Println(name, age)
      }
    }
    

    Program Output:

    0 apple
    1 banana
    2 orange
    Bob 30
    Charlie 35
    Alex 25

    It's also worth noting that the range keyword returns two values, the index, and the value. You can ignore the index by using the blank identifier _.

    Example:

    for _, value := range mySlice {
        fmt.Println(value)
    }
    

    break and continue Statements

    The "break" statement in Go programming is used to exit a loop early before the loop condition is re-evaluated. On the other hand, the "continue" statement is used to skip to the next iteration without exiting the loop.

    Here is an example of how the "break" statement can be used in a for loop:

    Example:

    package main
    import "fmt"
    
    func main() {
       for i := 1; i <= 5; i++ {
          if i == 5 {
             break
          }
          fmt.Println(i)
       }
    }

    In the example above, the loop will iterate from 0 to 4, then exit when "i" equals 5.

    Here is an example of how the "continue" statement can be used in a for loop:

    Example:

    package main
    import "fmt"
    
    func main() {
       for i := 0; i < 10; i++ {
          if i%2 == 0 {
             continue
          }
          fmt.Println(i)
       }
    }

    In the example above, the loop will iterate from 0 to 9, skipping the even numbers and only printing the odd numbers.



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.