0
0
Rustprogramming~10 mins

While loop in Rust - 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, updates variables, then checks again. It stops when the condition is false.
Execution Sample
Rust
let mut count = 0;
while count < 3 {
    println!("Count is {}", count);
    count += 1;
}
This code prints the count from 0 to 2 using a while loop that runs while count is less than 3.
Execution Table
StepcountCondition (count < 3)ActionOutput
10truePrint and increment count to 1Count is 0
21truePrint and increment count to 2Count is 1
32truePrint and increment count to 3Count is 2
43falseExit loop
💡 count reaches 3, condition 3 < 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
count01233
Key Moments - 2 Insights
Why does the loop stop when count is 3 even though the code increments count inside the loop?
The condition is checked before each loop iteration (see execution_table step 4). When count is 3, the condition count < 3 is false, so the loop exits before running the body again.
What happens if the condition is false at the start?
The loop body does not run at all. The condition is checked first (execution_table step 4 style), so if false initially, the loop exits immediately.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of count at step 2?
A1
B0
C2
D3
💡 Hint
Check the 'count' 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 where it changes to false.
If we change the condition to count < 2, how many times will the loop run?
A1 time
B3 times
C2 times
D0 times
💡 Hint
Refer to variable_tracker and execution_table to see how condition affects loop count.
Concept Snapshot
while condition {
    // code to run
}

- Checks condition before each loop
- Runs body only if condition true
- Stops when condition false
- Useful for repeating until a condition changes
Full Transcript
This visual execution shows how a while loop works in Rust. We start with a variable count set to 0. The loop checks if count is less than 3. If yes, it prints the count and adds 1 to it. This repeats until count reaches 3. Then the condition is false and the loop stops. The variable tracker shows count changing from 0 to 3 step by step. Key moments explain why the loop stops when count is 3 and what happens if the condition is false initially. The quiz questions help check understanding of the loop steps and variable changes.