Welcome to the fascinating world of Go programming! Today, we're diving deep into the "Go for Loop". This lesson is designed for both beginners and intermediates, so let's get started! 🚀
Loops are a fundamental part of programming that allow us to repeat a block of code multiple times. In Go, we have two types of loops: for loops and range loops. Today, we'll focus on the for loop.
for Loop 💡A simple for loop consists of three parts: the initialization, the condition, and the iteration.
for <initialization>; <condition>; <iteration> {
// Code to be repeated
}Let's understand this with an example:
package main
import "fmt"
func main() {
sum := 0
for i := 1; i <= 10; i++ {
sum += i
}
fmt.Println("Sum of numbers from 1 to 10:", sum)
}In this example, we initialize sum as 0, the condition is i <= 10, and the iteration happens when i++ is executed. The code inside the loop adds i to sum every time, until i is no longer less than or equal to 10.
What is the sum of numbers from 1 to 10 according to the given example?
for Loop 💡An infinite for loop occurs when the condition never becomes false. To avoid this, we should ensure that the loop has an explicit ending point.
package main
import "fmt"
func main() {
for {
fmt.Println("Hello, World!")
}
}In this example, we have an infinite loop that prints "Hello, World!" indefinitely. To stop the program, you'll need to use the Ctrl+C command in your terminal.
The break and continue keywords can be used to control the flow of the for loop.
break ends the loop immediately, skipping the remaining iterations.continue skips the current iteration and moves on to the next one.Here's an example using both:
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
if i%2 == 0 {
continue
}
fmt.Println(i)
}
}In this example, we print only odd numbers from 1 to 10. We use if i%2 == 0 to check if the number is even, and if it is, we use continue to skip that iteration and move on to the next one.
That's it for our introduction to Go for loops! Now, let's put your knowledge to the test with a small quiz.
What will be printed by the following code?
Keep practicing, and happy coding! 🎉