0
0
Cprogramming~10 mins

While loop in C - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While loop
Initialize variable
Check condition
|Yes
Execute loop body
Update variable
Back to Check
Exit loop
Back to Check
The while loop starts by checking a condition. If true, it runs the loop body and updates variables, then checks again. It stops when the condition is false.
Execution Sample
C
int i = 0;
while (i < 3) {
    printf("%d\n", i);
    i++;
}
Prints numbers 0, 1, 2 by repeating the loop while i is less than 3.
Execution Table
StepiCondition (i < 3)ActionOutput
10TruePrint 0, i = i + 10
21TruePrint 1, i = i + 11
32TruePrint 2, i = i + 12
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 is 3 even though the loop body is not executed?
Because the condition i < 3 is checked before the loop body each time (see execution_table step 4). When i is 3, the condition is false, so the loop exits immediately.
What happens if we forget to update i inside the loop?
The condition i < 3 will always be true if i starts less than 3, causing an infinite loop. The execution_table shows i increasing each step to avoid this.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i at step 3?
A3
B2
C1
D0
💡 Hint
Check the 'i' column in execution_table row 3.
At which step does the condition become false and the loop stops?
AStep 4
BStep 3
CStep 2
DStep 1
💡 Hint
Look at the 'Condition' column in execution_table to find when it is False.
If we remove 'i++' from the loop, what will happen?
AThe loop will stop immediately
BThe loop will print numbers 0 to 3
CThe loop will run forever printing 0
DThe program will crash
💡 Hint
Refer to key_moments about forgetting to update i causing infinite loop.
Concept Snapshot
while (condition) {
    // code to repeat
}

- Checks condition before each loop
- Runs code only if condition is true
- Updates inside loop needed to avoid infinite loops
- Stops when condition is false
Full Transcript
This example shows a while loop in C. We start with i = 0. The loop checks if i is less than 3. If yes, it prints i and adds 1 to i. This repeats until i reaches 3. When i is 3, the condition is false, so the loop stops. If we forget to increase i, the loop never ends because the condition stays true. The execution table shows each step with i's value, condition check, action, and output. This helps understand how the loop runs step-by-step.