0
0
Goprogramming~10 mins

For loop as while in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop as while
Initialize variable
Check condition
Yes
Execute loop body
Update variable
Back to Check
Exit loop
Back to Check
This flow shows how a for loop in Go can act like a while loop by initializing a variable, checking a condition before each iteration, running the loop body, updating the variable, and repeating until the condition is false.
Execution Sample
Go
package main
import "fmt"
func main() {
  i := 0
  for i < 3 {
    fmt.Println(i)
    i++
  }
}
This Go code uses a for loop like a while loop to print numbers 0, 1, and 2 by looping while i is less than 3.
Execution Table
Stepi valueCondition (i < 3)ActionOutput
10truePrint 0, i++0
21truePrint 1, i++1
32truePrint 2, i++2
43falseExit loop
💡 i reaches 3, condition i < 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 2 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes false at step 4 in the execution_table, so the loop exits before printing.
Is the variable i updated before or after printing?
The variable i is updated after printing in each loop iteration, 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 at step 2?
A1
B0
C2
D3
💡 Hint
Check the 'i value' column at step 2 in the execution_table.
At which step does the condition i < 3 become false?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look at the 'Condition (i < 3)' column in the execution_table.
If we change the condition to i < 2, how many times will the loop run?
A1 time
B3 times
C2 times
D0 times
💡 Hint
Refer to the variable_tracker and how the condition controls loop iterations.
Concept Snapshot
Go's for loop can act like a while loop:
- Initialize variable before loop
- Use for with condition only: for i < limit {
- Loop runs while condition true
- Update variable inside loop
- Stops when condition false
Full Transcript
This example shows how to use Go's for loop like a while loop by checking a condition before each iteration. We start with i = 0, then loop while i is less than 3. Each time, we print i and then increase it by one. When i reaches 3, the condition becomes false and the loop stops. The execution table tracks each step, showing the value of i, the condition check, the action taken, and the output printed. The variable tracker shows how i changes after each iteration. Key moments clarify why the loop stops and when i is updated. The quiz questions help check understanding by asking about i's value at certain steps and how changing the condition affects the loop count.