Mastering Conditional Logic in Loops with Go

Introduction to the Lesson

Welcome to our exploration of the combination of Go's for loop structures and conditional statements. By merging these elements together, your loops will become supercharged, enabling them to perform flexible and dynamic actions based on different conditions.

Reviewing Go Loop Structure

Before we forge ahead, it's essential to revisit the foundation: loops in Go. Go provides a highly versatile for loop. It's used not only for iterating over arrays, slices, and maps but also for emulating a while loop.

A for loop in Go iterates a predetermined number of times, much like a reliable spaceship following a set route:

Go
for i := 0; i < 5; i++ { // Iterates five times
    fmt.Println(i) // Prints 0 to 4
}

To act like a while loop, our for loop eliminates the initialization and increment portions:

Go
i := 0
for i < 5 { // Condition for the loop to continue
    fmt.Println(i) // Prints 0 to 4
    i++ // Increment the counter
}

Reviewing Go Conditional Statements

Now, let's revisit the if-else construct, which is Go's means for making decisions.

Go
asteroidsDistance := 10

if asteroidsDistance > 15 {
    fmt.Println("Navigate through the asteroids.")
} else {
    fmt.Println("Steer clear of the asteroids.")
}

The if-else statement enables the spaceship to decide whether to navigate through the asteroids based on their distance.

Combining Loops and Conditional Statements

Next, let's consider how the for loop integrates with an if-else statement:

Go
for i := 0; i < 6; i++ {
    if i % 2 == 0 {
        fmt.Println(i, "is even.")  // prints for 0, 2, and 4
    } else {
        fmt.Println(i, "is odd.")  // prints for 1, 3, and 5
    }
}   

Similarly, we can use an if-else statement within a for loop, which emulates a while loop:

Go
i := 0
for i < 7 { 
    if i % 3 == 0 {
        fmt.Println(i, "is divisible by 3.")  // will print for 0, 3, 6 
    } else {
        fmt.Println(i, "is not divisible by 3.")  // will print for 1, 2, 4, 5
    }
    i++
}

Real-life Examples: Part 1

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal