Introduction
Loop control helps manage how many times a loop runs. It stops loops from running forever and lets you skip or stop parts inside the loop.
Loop control helps manage how many times a loop runs. It stops loops from running forever and lets you skip or stop parts inside the loop.
for initialization; condition; post { // loop body // use break to exit loop early // use continue to skip to next iteration }
break stops the loop completely.
continue skips the rest of the current loop and moves to the next cycle.
for i := 0; i < 5; i++ { if i == 3 { break } fmt.Println(i) }
for i := 0; i < 5; i++ { if i == 2 { continue } fmt.Println(i) }
This program loops from 0 to 9. It skips even numbers and stops completely when it reaches 5.
package main import "fmt" func main() { for i := 0; i < 10; i++ { if i == 5 { fmt.Println("Stopping loop at", i) break } if i%2 == 0 { fmt.Println("Skipping even number", i) continue } fmt.Println("Number", i) } }
Without loop control, loops might run forever and crash your program.
Use break to exit loops early when you find what you need.
Use continue to skip unwanted steps but keep looping.
Loop control helps manage how loops run and stop.
break stops the loop completely.
continue skips to the next loop cycle.
break or continue required in Go loops?break and continue help decide when to stop or skip parts of a loop.for loop?continue skips the current iteration and moves to the next.break stops the loop entirely; skip and next are not valid Go keywords.for i := 1; i <= 5; i++ {
if i == 3 {
break
}
fmt.Print(i, " ")
}i == 3.for i := 0; i < 5; i++ {
if i == 2 {
continue
}
fmt.Println(i)
break
}i == 2, continue skips printing and break is after print, so loop stops after first iteration.Pass the test and this pattern moves unknown