0
0
Cprogramming~10 mins

For loop in C - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop
Initialize i=0
Check: i < 5?
NoEXIT
Yes
Execute body
Update: i = i+1
Back to Check
The for loop starts by setting a variable, then checks a condition. If true, it runs the loop body, updates the variable, and repeats. If false, it stops.
Execution Sample
C
for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}
Prints numbers 0 to 4, one per line, using a for loop.
Execution Table
Iterationi valueCondition (i < 5)ActionOutput
10TruePrint 00
21TruePrint 11
32TruePrint 22
43TruePrint 33
54TruePrint 44
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 i = 5, so the loop exits as shown in execution_table row 6.
When is the variable i updated in the loop?
i is updated after the loop body executes, before the next condition check, as seen between each iteration in variable_tracker.
Does the loop body run when the condition is false?
No, the loop body only runs when the condition is true. When i = 5, condition is false, so the loop body does not run (execution_table row 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i during the 3rd iteration?
A3
B1
C2
D4
💡 Hint
Check the 'i value' column in execution_table row 3.
At which iteration does the loop condition become false?
A6
B4
C5
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?
A5 times
B3 times
C2 times
D4 times
💡 Hint
Refer to the pattern in variable_tracker and execution_table for how condition controls iterations.
Concept Snapshot
for loop syntax in C:
for (initialization; condition; update) {
  // code to repeat
}

Loop runs while condition is true.
Variable updates after each iteration.
Stops when condition is false.
Full Transcript
A for loop in C starts by setting a variable, here i=0. It checks if i is less than 5. If yes, it runs the code inside the loop, printing i. Then it adds 1 to i. This repeats until i reaches 5, when the condition fails and the loop stops. The variable i changes from 0 up to 5, but the loop body runs only when i is 0 to 4. This is shown step-by-step in the execution table and variable tracker.