0
0
C++programming~10 mins

Loop execution flow in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Loop execution flow
Initialize loop variable
Check loop condition
NoExit loop
Yes
Execute loop body
Update loop variable
Back to Check loop condition
This flow shows how a loop starts by setting a variable, checks a condition, runs the loop body if true, updates the variable, and repeats until the condition is false.
Execution Sample
C++
for (int i = 0; i < 3; i++) {
    std::cout << i << std::endl;
}
This code prints numbers 0, 1, and 2 by looping while i is less than 3.
Execution Table
IterationiCondition (i < 3)ActionOutput
10truePrint 0, i++0
21truePrint 1, i++1
32truePrint 2, i++2
43falseExit loop
💡 i reaches 3, condition 3 < 3 is false, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 3 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes false at iteration 4 (see execution_table row 4), so the loop exits.
When is the variable i updated during the loop?
i is updated after the loop body executes in each iteration (see execution_table Action column), before the next condition check.
What happens if the initial condition is false?
The loop body does not run at all and the loop exits immediately (not shown here but implied by the flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i at iteration 2?
A0
B2
C1
D3
💡 Hint
Check the 'i' column in execution_table row for iteration 2.
At which iteration does the loop condition become false?
AIteration 4
BIteration 3
CIteration 1
DIteration 2
💡 Hint
Look at the Condition column in execution_table where it changes to false.
If we change the loop to i < 5, how many times will the loop run?
A3 times
B5 times
C4 times
D6 times
💡 Hint
The loop runs while i is less than the limit; check variable_tracker for i values.
Concept Snapshot
for (init; condition; update) {
  // loop body
}

1. Initialize variable
2. Check condition
3. Run body if true
4. Update variable
5. Repeat until condition false
Full Transcript
This example shows a for loop in C++ starting with i=0. Each step checks if i is less than 3. If yes, it prints i, then increases i by 1. This repeats until i reaches 3, when the condition fails and the loop stops. The variable i changes from 0 to 3 over the iterations. Key points are when the condition is checked and when i updates. The loop runs exactly three times, printing 0, 1, and 2.