for

path: courses/go-course/for.md

- **fileName**: for
- **Created on**: 2024-08-30 16:05:39

1. Basic for Loop

This is the traditional for loop with an initialization statement, a condition, and an iteration statement.

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

2. for Loop Without Initialization and Iteration

You can omit the initialization and iteration parts, making it act like a while loop. This will loop indefinitely until the condition is false.

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

3. Infinite for Loop

An infinite loop can be created by omitting all three parts of the for loop.

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

4. for Loop with range

When iterating over slices, arrays, maps, or strings, you can use the range keyword.

Slice 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)
    }
}

Map Example:

package main
import "fmt"
func main() {
    m := map[string]int{"a": 1, "b": 2, "c": 3}
    for key, value := range m {
        fmt.Printf("Key: %s, Value: %d\n", key, value)
    }
}

String Example:

package main

import "fmt"

func main() {
    s := "hello"
    for index, char := range s {
        fmt.Printf("Index: %d, Char: %c\n", index, char)
    }
}

5. for Loop With Only Condition

When you omit the initialization and iteration statements, the loop will only check the condition.


package main

import "fmt"

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

6. for Loop With Only Initialization

It’s possible to have only an initialization statement, and then use an infinite loop with a conditional break.


package main

import "fmt"

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

continue:err-go.md
before:if-statement.md