Go Loops

Repeating code execution efficiently

πŸ”„ What are Go Loops?

Go loops allow you to execute code repeatedly until a condition is met. Go has only one loop keyword 'for' but it can be used in multiple ways to create different loop patterns.


// Simple loop example
for i := 1; i <= 3; i++ {
    fmt.Printf("Count: %d\n", i)
}
                                    

Output:

Count: 1

Count: 2

Count: 3

Types of For Loops

πŸ”’

Classic For

Traditional three-part loop structure

for i := 0; i < 5; i++ {
    fmt.Println(i)
}
⏳

While-style

Loop with only condition

i := 0
for i < 5 {
    fmt.Println(i)
    i++
}
♾️

Infinite Loop

Loop that runs forever

for {
    fmt.Println("Forever")
    break // Exit condition
}
πŸ“‹

Range Loop

Iterate over collections

nums := []int{1, 2, 3}
for i, v := range nums {
    fmt.Println(i, v)
}

πŸ”Ή Classic For Loop

The traditional three-part for loop:

package main

import "fmt"

func main() {
    // Print numbers 1 to 5
    for i := 1; i <= 5; i++ {
        fmt.Printf("Number: %d\n", i)
    }
    
    fmt.Println("Loop finished!")
}

Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

Loop finished!

πŸ”Ή While-style Loop

Loop with only a condition (like while in other languages):

package main

import "fmt"

func main() {
    count := 0
    
    for count < 3 {
        fmt.Printf("Count is: %d\n", count)
        count++
    }
    
    fmt.Println("Done counting!")
}

Output:

Count is: 0

Count is: 1

Count is: 2

Done counting!

πŸ”Ή Infinite Loop with Break

Loop forever until a break condition is met:

package main

import "fmt"

func main() {
    counter := 0
    
    for {
        fmt.Printf("Iteration: %d\n", counter)
        counter++
        
        if counter >= 3 {
            fmt.Println("Breaking out of loop!")
            break
        }
    }
    
    fmt.Println("After loop")
}

Output:

Iteration: 0

Iteration: 1

Iteration: 2

Breaking out of loop!

After loop

πŸ”Ή Continue Statement

Skip the current iteration and continue with the next:

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 3 {
            fmt.Println("Skipping 3")
            continue
        }
        fmt.Printf("Processing: %d\n", i)
    }
}

Output:

Processing: 1

Processing: 2

Skipping 3

Processing: 4

Processing: 5

πŸ”Ή Nested Loops

Loops inside other loops for complex iterations:

package main

import "fmt"

func main() {
    fmt.Println("Multiplication Table:")
    
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            result := i * j
            fmt.Printf("%d x %d = %d  ", i, j, result)
        }
        fmt.Println() // New line after each row
    }
}

Output:

Multiplication Table:

1 x 1 = 1 1 x 2 = 2 1 x 3 = 3

2 x 1 = 2 2 x 2 = 4 2 x 3 = 6

3 x 1 = 3 3 x 2 = 6 3 x 3 = 9

🧠 Test Your Knowledge

What is the only loop keyword in Go?