Lesson 3
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
1for i := 0; i < 5; i++ { // Iterates five times 2 fmt.Println(i) // Prints 0 to 4 3}

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

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

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

Go
1asteroidsDistance := 10 2 3if asteroidsDistance > 15 { 4 fmt.Println("Navigate through the asteroids.") 5} else { 6 fmt.Println("Steer clear of the asteroids.") 7}

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

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

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

Consider an application designed to monitor oxygen levels across a network of stations. These stations are critical for ensuring the safety and well-being of personnel in a space habitat. The following example demonstrates how we can iterate through an array of oxygen sensor readings and apply conditional logic to alert us to potential dangers.

Go
1oxygenReadings := []float64{21.5, 20.9, 19.2, 18.0, 22.1} // Oxygen levels of different stations 2safeOxygenLevel := 19.5 // Minimum safe level in percentage 3 4for i, reading := range oxygenReadings { 5 if reading < safeOxygenLevel { 6 fmt.Printf("Warning! Low oxygen level at Station %d. \n", i+1) 7 // will print for stations 3 and 4 8 } else { 9 fmt.Printf("Station %d oxygen level is safe.\n", i+1) 10 // will print for stations 1, 2 and 5 11 } 12}

In this code, oxygenReadings holds the oxygen percentages reported by sensors at each station. By looping through these readings, we can identify any station with an oxygen level below the designated safe threshold (safeOxygenLevel). The loop then prints a customized message for each station, using a conditional statement to determine whether the situation is safe or requires an alert.

Real-life Examples: Part 2

In another scenario, consider a game. As long as the game is on—represented by a for loop—if you hit an alien, represented as an if condition, you gain points!

For random generation of successful/unsuccessful hit, we will need to import "math/rand":

Go
1import ( 2 "fmt" 3 "math/rand" 4)
Go
1score := 0 2gameOn := true 3 4for gameOn { 5 isAlienHit := rand.Intn(2) // Random generator for hit (1) or miss (0) 6 7 if isAlienHit == 1 { 8 fmt.Println("Alien vessel hit! +10 points") 9 score += 10 10 } else { 11 fmt.Println("Missed! Game Over.") 12 gameOn = false 13 } 14} 15fmt.Println("Your score is", score) // Displays the final score when the game ends.
Lesson Summary and Practice

You've now learned how to effectively combine Go's for loops and if-else statements. Prepare yourself for some engaging practice to further solidify these exciting programming skills! You're well on your way to tackling more complex problems in Go. Embark on a fulfilling journey!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.