Concept Flow - Break statement
Start Loop
Check Condition
Yes
Execute Loop Body
Check Break Condition
Break Loop
End Loop
The loop starts and runs while the condition is true. Inside, if the break condition is met, the loop stops immediately.
package main import "fmt" func main() { for i := 1; i <= 5; i++ { if i == 3 { break } fmt.Println(i) } }
| Iteration | i | Condition i <= 5 | Break Condition i == 3 | Action | Output |
|---|---|---|---|---|---|
| 1 | 1 | true | false | Print 1 | 1 |
| 2 | 2 | true | false | Print 2 | 2 |
| 3 | 3 | true | true | Break loop | |
| 4 | - | Loop exited | - | - | - |
| Variable | Start | After 1 | After 2 | After 3 (break) | Final |
|---|---|---|---|---|---|
| i | - | 1 | 2 | 3 | 3 |
Break statement in Go:
- Used inside loops to stop the loop immediately.
- Syntax: break
- When break runs, loop exits even if condition is true.
- Useful to stop early based on a condition.
- Example: if i == 3 { break } stops loop when i is 3.