0
0
Goprogramming~10 mins

Break statement in Go - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Go
package main
import "fmt"
func main() {
  for i := 1; i <= 5; i++ {
    if i == 3 {
      break
    }
    fmt.Println(i)
  }
}
This code prints numbers 1 and 2, then stops the loop when i equals 3 using break.
Execution Table
IterationiCondition i <= 5Break Condition i == 3ActionOutput
11truefalsePrint 11
22truefalsePrint 22
33truetrueBreak loop
4-Loop exited---
💡 Loop stops at iteration 3 because break condition i == 3 is true.
Variable Tracker
VariableStartAfter 1After 2After 3 (break)Final
i-1233
Key Moments - 2 Insights
Why does the loop stop printing after i equals 3 even though the loop condition i <= 5 is true?
Because the break statement runs when i == 3 (see execution_table row 3), it immediately exits the loop before printing.
Does the break statement skip only the current iteration or the entire loop?
The break statement stops the entire loop immediately, not just skipping one iteration (see execution_table row 3 action).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i when the break statement is executed?
A1
B2
C3
D4
💡 Hint
Check the 'Break Condition i == 3' column in row 3 of the execution_table.
At which iteration does the loop stop running?
AAfter iteration 2
BAt iteration 3
CAt iteration 4
DAfter iteration 5
💡 Hint
Look at the 'Action' column in the execution_table where it says 'Break loop'.
If the break condition was changed to i == 4, what would be the last number printed?
A4
B5
C3
D2
💡 Hint
Think about when the break would stop the loop and what numbers print before that (see variable_tracker and execution_table).
Concept Snapshot
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.
Full Transcript
This visual execution shows how the break statement works in a Go for loop. The loop runs from i = 1 to 5. Each iteration prints i unless i equals 3. When i is 3, the break statement runs and stops the loop immediately. This means the loop does not continue to 4 or 5. The variable i changes from 1 to 3, and the loop exits at 3. The key moment is understanding that break stops the whole loop, not just one iteration. The quiz questions help check your understanding of when and why the loop stops.