Loops & Control Flow
Go keeps syntax clean and minimal. It features only one loop construct: the for loop, which is used to implement standard, while, and range loops.
1 The Single Loop Construct: for
Go implements all loop configurations using the `for` keyword:
- Standard For Loop: `for i := 0; i < 5; i++ {}`
- While Loop representation: `for condition {}` (Omit initializer and increment statements).
- Infinite Loop: `for {}` (Omit all parameters).
2 Loop Control & range Traversal
Let's run a program illustrating standard loops, while loops, and using break/continue:
Go — For Loops
▶ Run Code
package main
import "fmt"
func main() {
// 1. Standard For Loop
fmt.Print("Standard For: ")
for i := 1; i <= 5; i++ {
fmt.Printf("%d ", i)
}
fmt.Println()
// 2. While loop representation
fmt.Print("While representation (skipping 3, breaking at 6): ")
count := 1
for count <= 10 {
if count == 3 {
count++
continue; // Skip the rest of this loop iteration
}
if count == 6 {
break; // Exit the loop entirely
}
fmt.Printf("%d ", count)
count++
}
fmt.Println()
}
3 Code Challenge
Challenge: Write a loop that sums all odd numbers between 1 and 20. Skip the number 11 using the `continue` keyword, and print the computed sum at the end.