In the previous lesson, we used an infinite for loop with a break statement to control when to exit. Go provides a cleaner way to handle this common pattern: adding a condition directly to the for loop.
Instead of an infinite loop with break, you can specify a condition that's checked before each iteration. The loop continues as long as the condition is true.
counter := 0
for counter < 5 {
fmt.Println(counter)
counter++
}
// Prints: 0, 1, 2, 3, 4
This is similar to a while loop in other programming languages, but Go uses for for all looping needs.
The loop checks the condition before each iteration:
power := 1
for power < 100 {
fmt.Println("Power level:", power)
power = power * 2
}
// Prints: 1, 2, 4, 8, 16, 32, 64
Once power reaches 128, the condition power < 100 becomes false, and the loop exits.
Compare these two approaches that accomplish the same thing:
// Using infinite loop with break
count := 0
for {
if count >= 3 {
break
}
fmt.Println(count)
count++
}
// Using conditional loop - cleaner!
count := 0
for count < 3 {
fmt.Println(count)
count++
}
The conditional loop is more readable and conventional when you have a simple condition to check.
// Use conditional loops when you have a clear stopping condition
attempts := 0
for attempts < 5 {
fmt.Println("Attempt:", attempts)
attempts++
}
// Use infinite loops with break for more complex exit conditions
for {
userInput := getUserInput()
if userInput == "quit" || errorOccurred {
break
}
processInput(userInput)
}
For this challenge, create a function called countdown that accepts a parameter n (an int).
The function should:
for loop with a condition (not an infinite loop)n and count down to 1Important: If n is 0 or negative, the loop should not run at all.
The function signature is:
func countDown(n int) {
// Your code here
}
For example, calling countDown(5) should print:
5
4
3
2
1