Go supports the traditional C-style for loop syntax, which combines initialization, condition, and increment into a single, compact line. This is the most common form of loop you'll see in Go code.
The C-style loop has three components separated by semicolons:
for initialization; condition; post {
// loop body
}
Here's a simple example:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Prints: 0, 1, 2, 3, 4
Let's understand each part:
i := 0): Runs once before the loop startsi < 5): Checked before each iteration; loop continues while truei++): Runs after each iterationfor i := 1; i <= 10; i++ {
fmt.Println("Count:", i)
}
This prints numbers 1 through 10.
Here's the order of operations:
for i := 0; i < 3; i++ {
fmt.Println(i)
}
// Execution order:
// 1. i := 0 (initialization - once)
// 2. Check i < 3? Yes (0 < 3) ✓
// 3. Print 0
// 4. i++ (now i = 1)
// 5. Check i < 3? Yes (1 < 3) ✓
// 6. Print 1
// 7. i++ (now i = 2)
// 8. Check i < 3? Yes (2 < 3) ✓
// 9. Print 2
// 10. i++ (now i = 3)
// 11. Check i < 3? No (3 < 3) ✗
// 12. Exit loop
You can also count backwards by using different operators:
for i := 5; i > 0; i-- {
fmt.Println(i)
}
// Prints: 5, 4, 3, 2, 1
The post statement doesn't have to be just ++ or --:
// Count by 2s
for i := 0; i < 10; i += 2 {
fmt.Println(i)
}
// Prints: 0, 2, 4, 6, 8
// Count by 10s
for i := 0; i <= 100; i += 10 {
fmt.Println(i)
}
// Prints: 0, 10, 20, 30, ..., 100
All three of these accomplish the same thing:
// C-style for loop - most compact and common
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Conditional loop
i := 0
for i < 5 {
fmt.Println(i)
i++
}
// Infinite loop with break
i := 0
for {
if i >= 5 {
break
}
fmt.Println(i)
i++
}
The C-style loop is preferred when you know exactly how many iterations you need.
For this challenge, create a function called printMultiples that accepts two parameters: n (an int) and max (an int).
The function should:
for loopn from n up to (but not exceeding) maxFor example:
printMultiples(3, 10) should print: 3, 6, 9 each on new lineprintMultiples(5, 25) should print: 5, 10, 15, 20, 25The function signature is:
func printMultiples(n int, max int) {
// Your code here
}