0
0
Goprogramming~10 mins

For loop basics in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop basics
Initialize i=0
Check: i < 5?
NoEXIT
Yes
Execute body
Update: i = i+1
Back to Check
The loop starts by setting i to 0, then checks if i is less than 5. If yes, it runs the loop body, then increases i by 1 and repeats. If no, it stops.
Execution Sample
Go
for i := 0; i < 5; i++ {
    fmt.Println(i)
}
This code prints numbers from 0 to 4 using a for loop.
Execution Table
IterationiCondition i<5ActionOutput
10truePrint i=0, i++0
21truePrint i=1, i++1
32truePrint i=2, i++2
43truePrint i=3, i++3
54truePrint i=4, i++4
65falseExit loop
💡 i reaches 5, condition 5 < 5 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
i0123455
Key Moments - 3 Insights
Why does the loop stop when i equals 5?
Because the condition i < 5 becomes false at iteration 6, as shown in the execution_table row 6.
Does the loop print the number 5?
No, the loop stops before printing 5 because the condition i < 5 is false when i is 5, as seen in execution_table row 6.
When is the variable i increased?
i is increased after printing in each iteration, before the next condition check, as shown in the Action column of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i during iteration 3?
A2
B3
C1
D0
💡 Hint
Check the 'i' column in execution_table row 3.
At which iteration does the condition i < 5 become false?
A5
B6
C4
D1
💡 Hint
Look at the 'Condition i<5' column in execution_table row 6.
If we change the loop to i < 3, how many times will the loop run?
A2 times
B5 times
C3 times
D4 times
💡 Hint
Compare the condition i < 5 with i < 3 and count iterations accordingly.
Concept Snapshot
Go for loop syntax:
for initialization; condition; post {
    // code
}
Loop runs while condition is true.
Variable updates after each iteration.
Stops when condition is false.
Full Transcript
This visual trace shows a Go for loop starting with i=0. Each step checks if i is less than 5. If true, it prints i and then increases i by 1. This repeats until i reaches 5, when the condition fails and the loop stops. The variable tracker shows i's value changing from 0 up to 5. Key moments clarify why the loop stops before printing 5 and when i increments. The quiz tests understanding of variable values and loop stopping conditions.