Day 4: Looping with For in Go, Comprehensive Guide to Loops in Go: For Loops

Venkat Annangi
Venkat Annangi
23/09/2024 15:41 2 min read 36 views
#golang #108 days of golang

Day 4: Comprehensive Guide to Loops in Go - For Loops

Today we’ll focus on the for loop. Go only has one loop construct, but it’s versatile enough to cover a wide range of scenarios, including traditional for loops, while loops, and infinite loops.

Step 1: Basic For Loop

The basic for loop in Go is similar to C-style loops:

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

Step 2: Range Loops

Go provides the range keyword to iterate over arrays, slices, maps, and strings:

numbers := []int{1, 2, 3, 4, 5}
for i, num := range numbers {
    fmt.Printf("Index: %d, Value: %d\n", i, num)
}

Step 3: Infinite Loops

If you omit the loop condition, you create an infinite loop:

for {
    fmt.Println("This will run forever")
}

Step 4: Breaking and Continuing

You can control the flow using break and continue statements:

for i := 0; i < 10; i++ {
    if i%2 == 0 {
        continue  // Skip even numbers
    }
    if i > 7 {
        break  // Stop the loop if i > 7
    }
    fmt.Println(i)
}

Practical Exercise

Write a Go program to loop through an array of numbers and calculate their sum. Then modify it to skip negative numbers and stop the loop if a number greater than 108 is found.

Comments