Exercise 5: Loops and Conditions in Go

In this exercise, you'll learn how to use loops and conditions to control the flow of execution in your program.

Exercise Objectives:

1. Use loops to repeat actions.
2. Apply conditions (`if`, `else if`, `else`) to execute code blocks based on test results.
3. Understand how to manipulate data sequences using loops and conditions.

Loops in Go:

Loops allow you to repeat a block of code multiple times. In Go, the primary loop structure is the `for` loop, which is very flexible.

  • Example of a simple `for` loop:
  • for i := 1; i <= 10; i++ {
        fmt.Println(i)
    }
  • Explanation: This loop starts at `i = 1` and runs while `i <= 10`, incrementing `i` by 1 on each iteration.
  • The `for` loop can also function like a `while` loop:
  • i := 1
    for i <= 10 {
        fmt.Println(i)
        i++
    }

Conditions in Go:

Conditions allow you to execute code only when a specific condition is met. In Go, `if`, `else if`, and `else` statements are commonly used.

  • Example of a simple condition:
  • if i % 2 == 0 {
        fmt.Println("The number is even")
    } else {
        fmt.Println("The number is odd")
    }

Exercise Instructions:

Create a file named loops_conditions.go and follow these steps:

  1. Use a `for` loop to iterate from 1 to 10.
  2. For each iteration, apply a condition:
    • If the number is even, print "Number X is even".
    • If the number is odd, print "Number X is odd".
    • Add a special condition to print "Number 5 is special!" when the number is 5.
  3. package main
    
    import "fmt"
    
    func main() {
        for i := 1; i <= 10; i++ {
            if i % 2 == 0 {
                fmt.Println(i, "is even")
            } else {
                fmt.Println(i, "is odd")
            }
    
            if i == 5 {
                fmt.Println("Number 5 is special!")
            }
        }
    }

Expected Output:

1 is odd
2 is even
3 is odd
4 is even
Number 5 is special!
6 is even
7 is odd
8 is even
9 is odd
10 is even

Learn More:

For more details on loops and conditions in Go, check the official Go documentation:

Go Loops and Conditions Documentation
← Previous Exercise Next Exercise →

🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee