0
0
Goprogramming~10 mins

Nested loops in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Nested loops
Start outer loop i=0
Start inner loop j=0
Execute inner loop body
Update inner loop j=j+1
Check inner loop j < limit?
YesRepeat inner loop body
No
Update outer loop i=i+1
Check outer loop i < limit?
YesRepeat inner loop
No
End
The outer loop runs first. For each outer loop step, the inner loop runs completely. Then the outer loop moves to the next step.
Execution Sample
Go
for i := 0; i < 2; i++ {
    for j := 0; j < 3; j++ {
        fmt.Println(i, j)
    }
}
Print pairs of i and j where i goes 0 to 1 and j goes 0 to 2 for each i.
Execution Table
StepijCondition i<2Condition j<3ActionOutput
100truetruePrint (0,0)(0 0)
201truetruePrint (0,1)(0 1)
302truetruePrint (0,2)(0 2)
403truefalseInner loop ends
510truetruePrint (1,0)(1 0)
611truetruePrint (1,1)(1 1)
712truetruePrint (1,2)(1 2)
813truefalseInner loop ends
920falsetrueOuter loop ends
💡 Outer loop i=2 fails condition i<2, so loops stop.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6After 7After 8Final
i0000011112
j0123012300
Key Moments - 3 Insights
Why does j reset to 0 after inner loop ends?
Because j is declared inside the inner loop, it starts fresh each time the inner loop begins (see rows 4 and 5 in execution_table).
Why does the outer loop increment only after inner loop finishes?
The outer loop waits for the inner loop to complete all its steps before increasing i (see transition from row 4 to 5).
What stops the loops from running forever?
The conditions i<2 and j<3 become false eventually, stopping loops (see rows 4 and 9 where conditions fail).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of j at step 6?
A2
B1
C0
D3
💡 Hint
Check the 'j' column in row 6 of the execution_table.
At which step does the outer loop condition become false?
AStep 9
BStep 8
CStep 4
DStep 7
💡 Hint
Look at the 'Condition i<2' column and find where it is false.
If the inner loop condition changed to j<2, how many times would the inner loop print per outer loop iteration?
A3 times
B1 time
C2 times
D4 times
💡 Hint
Check how many times j runs from 0 while j<2 in the variable_tracker.
Concept Snapshot
Nested loops run one loop inside another.
Outer loop runs first.
Inner loop runs fully for each outer loop step.
Inner loop variable resets each time.
Loops stop when conditions fail.
Full Transcript
This example shows nested loops in Go. The outer loop variable i starts at 0 and runs while less than 2. For each i, the inner loop variable j runs from 0 to less than 3. Each pair (i,j) is printed. The inner loop finishes all its steps before the outer loop increments i. Variables i and j change as loops run. The loops stop when conditions become false. This helps understand how loops inside loops work step-by-step.