BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: For Loops

Go 1.23

Go has only one looping construct: the `for` loop. However, it is versatile enough to act as a standard counter loop, a while loop, and an infinite loop. This example demonstrates all three patterns.

Code

package main

import "fmt"

func main() {
    // 1. Standard Counter Loop
    // The classic C-style for loop: init; condition; post
    for i := 0; i < 3; i++ {
        fmt.Println("Counter:", i)
    }

    // 2. While Loop Equivalent
    // You can omit the init and post statements.
    // This behaves exactly like a 'while' loop in other languages.
    n := 1
    for n < 5 {
        fmt.Println("While-style:", n)
        n *= 2
    }

    // 3. Infinite Loop
    // Omitting everything creates an infinite loop.
    // Use 'break' to exit or 'return' to return from function.
    sum := 0
    for {
        sum++
        if sum >= 10 {
            fmt.Println("Reached target, breaking...")
            break // Exit the loop
        }
    }

    // 4. Continue Statement
    // Skips the rest of the current iteration.
    for i := 0; i <= 5; i++ {
        if i%2 == 0 {
            continue // Skip even numbers
        }
        fmt.Println("Odd:", i)
    }
}

Explanation

Go simplifies control flow by having only one keyword for looping: for. There are no while or do-while keywords. Instead, the for loop is flexible enough to handle all iteration scenarios.

The three basic forms are:

  1. Standard: for i := 0; i < 10; i++. Used for iterating a specific number of times.
  2. Condition-only (While): for x < 100. Used when you want to loop as long as a condition is true.
  3. Infinite: for { ... }. Used for servers, event loops, or when the exit condition is complex and checked internally with break.

Inside any loop, you can use break to exit immediately or continue to jump to the next iteration. This minimalist approach reduces the number of keywords to learn while maintaining full power.

Code Breakdown

8-10
The classic for-loop. It initializes 'i', checks if 'i < 3', runs the body, and then increments 'i'. The scope of 'i' is limited to the loop body.
16-19
The "while" loop pattern. By omitting the semicolons, Go understands this as a condition-only loop. It runs as long as 'n < 5' is true.
25-31
The infinite loop. 'for { ... }' will run forever unless interrupted. Here, we manually check a condition and use the 'break' keyword to escape the loop.
37
The 'continue' keyword. When executed, it immediately stops the current iteration and jumps to the post-statement (i++), effectively skipping the print statement for even numbers.