Loops allow you to execute code repeatedly without writing the same statements over and over. In Go, there's only one looping construct: the for loop. However, it's incredibly flexible and can be used in many different ways.
The simplest form of a for loop in Go is an infinite loop - a loop that runs forever (or until you tell it to stop).
for {
fmt.Println("This will run forever!")
}
This might seem scary, but it's actually quite useful when combined with ways to exit the loop.
The break keyword allows you to exit a loop early, giving you full control over when to stop looping.
count := 0
for {
fmt.Println("Looping...")
count++
if count == 3 {
break // Exit the loop when count reaches 3
}
}
fmt.Println("Loop finished!")
This will print "Looping..." exactly 3 times, then exit the loop and print "Loop finished!".
The loop runs continuously until it encounters a break statement. This pattern gives you complete control over when to exit based on any condition you want.
userInput := ""
for {
fmt.Println("Enter 'quit' to exit:")
// (imagine getting user input here)
if userInput == "quit" {
break
}
fmt.Println("You entered:", userInput)
}
A common pattern is to use a counter variable to track how many times the loop has run.
iterations := 0
for {
fmt.Println("Iteration:", iterations)
iterations++
if iterations == 5 {
break
}
}
// Prints 5 times (iterations 0 through 4)
For this challenge, create a function called countUp that accepts a parameter n (an integer).
The function should:
for loopif statement to check when the counter equals nbreak to exit the loop when the counter reaches nThe function signature is:
func countUp(n int) {
// Your code here
}
For example, calling countUp(3) should print:
0
1
2