0
0
C++programming~10 mins

While loop in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While loop
Initialize variable
Check condition
Execute loop body
Update variable
Back to Check condition
The while loop checks a condition before each iteration. If true, it runs the loop body and updates variables, then checks again. If false, it exits.
Execution Sample
C++
#include <iostream>
using namespace std;

int main() {
    int i = 0;
    while (i < 3) {
        cout << i << " ";
        i++;
    }
    return 0;
}
This code prints numbers 0, 1, 2 by looping while i is less than 3.
Execution Table
Stepi valueCondition (i < 3)ActionOutput
10truePrint 0, i = i + 10
21truePrint 1, i = i + 11
32truePrint 2, i = i + 12
43falseExit loop
💡 i reaches 3, condition 3 < 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 (see execution_table row 4), so the loop exits.
What happens if we forget to update i inside the loop?
The condition i < 3 would always be true, causing an infinite loop because i never changes (no progress).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i at step 2?
A0
B2
C1
D3
💡 Hint
Check the 'i value' column in execution_table row 2.
At which step does the condition become false and the loop stops?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look at the 'Condition' column in execution_table to find when it is false.
If we change the condition to i < 2, how many times will the loop run?
A2 times
B1 time
C3 times
D0 times
💡 Hint
Check variable_tracker and think when i reaches 2, condition i < 2 becomes false.
Concept Snapshot
while (condition) {
    // code to repeat
    // update variables
}

- Checks condition before each loop
- Runs body only if condition true
- Updates variables inside to avoid infinite loop
- Stops when condition is false
Full Transcript
A while loop starts by checking a condition. If the condition is true, it runs the code inside the loop body. Then it updates variables, usually to move toward stopping the loop. It repeats this check and run cycle until the condition becomes false, then it exits. For example, starting with i = 0, while i is less than 3, it prints i and increases i by 1. When i reaches 3, the condition fails and the loop stops. Forgetting to update i causes an infinite loop because the condition never becomes false.