In this exercise, you'll learn how to use loops and conditions to control the flow of execution in your program.
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 allow you to repeat a block of code multiple times. In Go, the primary loop structure is the `for` loop, which is very flexible.
for i := 1; i <= 10; i++ {
fmt.Println(i)
}
i := 1
for i <= 10 {
fmt.Println(i)
i++
}
Conditions allow you to execute code only when a specific condition is met. In Go, `if`, `else if`, and `else` statements are commonly used.
if i % 2 == 0 {
fmt.Println("The number is even")
} else {
fmt.Println("The number is odd")
}
Create a file named loops_conditions.go
and follow these steps:
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!")
}
}
}
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
For more details on loops and conditions in Go, check the official Go documentation:
Go Loops and Conditions Documentation🚀 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! ☕😊