0
0
C Sharp (C#)programming~10 mins

While loop execution model in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While loop execution model
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, updates variables, then checks again. It stops when the condition is false.
Execution Sample
C Sharp (C#)
int i = 0;
while (i < 3) {
    Console.WriteLine(i);
    i++;
}
This code prints numbers 0, 1, and 2 by looping 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 3 < 3 is False, loop stops
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 step 4, so the loop exits as shown in the execution_table row 4.
When is the variable i updated in the loop?
i is updated after printing in each iteration, as shown in the Action column of rows 1 to 3 in the execution_table.
Does the loop body run if the condition is false at the start?
No, the condition is checked before the loop body runs. If false initially, the loop body never executes.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i at step 2?
A1
B0
C2
D3
💡 Hint
Check the 'i' column in execution_table row 2.
At which step does the condition become false?
AStep 3
BStep 4
CStep 1
DStep 2
💡 Hint
Look at the Condition column in execution_table to find when it is False.
If we start i at 2 instead of 0, how many times will the loop run?
A3 times
B2 times
C1 time
D0 times
💡 Hint
Refer to variable_tracker and think how many increments before i < 3 is false.
Concept Snapshot
while (condition) {
    // code runs while condition is true
}

- Condition checked before each loop
- Loop body runs only if condition true
- Update variables inside loop to avoid infinite loop
- Stops when condition is false
Full Transcript
This visual execution model shows how a while loop works in C#. It starts by initializing a variable i to 0. Then it checks if i is less than 3. If true, it prints i and increases i by 1. This repeats until i reaches 3, when the condition becomes false and the loop stops. The execution table tracks each step, showing variable values, condition results, actions, and outputs. Key moments clarify common confusions like when the loop stops and when variables update. The quiz tests understanding by asking about variable values and loop behavior. The snapshot summarizes the while loop syntax and rules.