Welcome to our deep dive into the fascinating world of Go programming! Today, we're going to explore two powerful control flow statements: break and continue. These statements can help you navigate loops with greater precision and control.
The break statement is used to exit a loop (for, while, or switch) prematurely. By understanding how break works, you can write more efficient and effective code.
Here's a simple example demonstrating the break statement:
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i == 5 {
fmt.Println("Breaking the loop at 5")
break
}
fmt.Println("Loop Iteration:", i)
}
}When you run this code, you'll see output like this:
Loop Iteration: 0
Loop Iteration: 1
Loop Iteration: 2
Loop Iteration: 3
Loop Iteration: 4
Breaking the loop at 5
š Note: The loop stops executing once the break statement is encountered.
The continue statement is used to skip the current iteration of a loop and proceed to the next one. This can be incredibly useful when you want to avoid processing certain iterations based on specific conditions.
Let's examine a simple example of the continue statement:
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue
}
fmt.Println("Odd numbers:", i)
}
}When you run this code, the output will be:
Odd numbers: 1
Odd numbers: 3
Odd numbers: 5
Odd numbers: 7
Odd numbers: 9
š Note: The loop skips even numbers and only processes odd numbers.
Create a program that finds all prime numbers between 1 and 100 using the continue statement.
package main
import "fmt"
func main() {
// Your code here š
}You can find the solution to this exercise here. Try to understand how it works, and you'll have a deeper understanding of the continue statement.
Happy coding! š