0
0
C++programming~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 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
C++
for (int i = 0; i < 5; i++) {
    std::cout << i << std::endl;
}
Prints numbers from 0 to 4, one per line.
Execution Table
IterationiCondition (i < 5)ActionOutput
10truePrint 0, i++0
21truePrint 1, i++1
32truePrint 2, i++2
43truePrint 3, i++3
54truePrint 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 is 5 even though we print numbers starting from 0?
The loop condition checks if i < 5. When i becomes 5, this condition is false, so the loop stops before printing 5. See execution_table row 6.
When exactly does i increase in the loop?
i increases after the loop body runs, before the next condition check. This is shown in execution_table where 'i++' happens after printing.
What happens if we change i++ to i += 2?
i would increase by 2 each time, so the loop runs fewer times. The variable_tracker would show i values jumping by 2 instead of 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i during the 3rd iteration?
A1
B3
C2
D0
💡 Hint
Check the 'i' column in the execution_table row labeled '3'
At which iteration does the loop condition become false?
A5
B6
C4
D1
💡 Hint
Look at the 'Condition (i < 5)' column in the execution_table where it is false
If we change i++ to i += 2, how would the variable_tracker change after the first iteration?
Ai would be 2 instead of 1
Bi would be 0 instead of 1
Ci would be 3 instead of 1
Di would not change
💡 Hint
Refer to variable_tracker and think how i increments by 2 instead of 1
Concept Snapshot
for loop syntax: for (init; condition; update) { body }
Runs body while condition is true.
Init runs once at start.
Update runs after each body execution.
Stops when condition is false.
Full Transcript
A for loop in C++ starts by initializing a variable, here i=0. Then it checks if i is less than 5. If yes, it runs the loop body which prints i. After that, i increases by 1. This repeats until i reaches 5, when the condition becomes false and the loop stops. The variable i changes from 0 up to 5, but 5 is not printed because the loop stops before printing it.