0
0
Rustprogramming~10 mins

Loop execution flow in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Loop execution flow
Initialize counter i=0
Check condition i < 3?
NoEXIT LOOP
Yes
Execute loop body
Update counter i = i + 1
Back to condition check
The loop starts by setting a counter, checks if it meets the condition, runs the loop body if yes, updates the counter, and repeats until the condition is false.
Execution Sample
Rust
fn main() {
    let mut i = 0;
    while i < 3 {
        println!("i = {}", i);
        i += 1;
    }
}
This Rust code runs a loop printing the value of i from 0 to 2.
Execution Table
Stepi valueCondition i < 3?ActionOutput
10truePrint i, i = 0; i = i + 1i = 0
21truePrint i, i = 1; i = i + 1i = 1
32truePrint i, i = 2; i = i + 1i = 2
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 equals 3?
Because the condition i < 3 becomes false at step 4 in the execution_table, so the loop exits.
When is the value of i increased during the loop?
After printing i in each iteration, i is increased by 1 as shown in the Action column of steps 1 to 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i at step 2?
A2
B0
C1
D3
💡 Hint
Check the 'i value' column at step 2 in the execution_table.
At which step does the loop condition become false?
AStep 4
BStep 3
CStep 1
DStep 2
💡 Hint
Look at the 'Condition i < 3?' column in the execution_table.
If we change the condition to i < 2, how many times will the loop run?
A3 times
B2 times
C1 time
D0 times
💡 Hint
Refer to the variable_tracker and how the condition controls loop iterations.
Concept Snapshot
Rust loop execution flow:
- Initialize counter before loop
- Check condition before each iteration
- Run loop body if condition true
- Update counter inside loop
- Repeat until condition false
- Loop exits cleanly
Full Transcript
This example shows a Rust while loop starting with i = 0. Each step checks if i is less than 3. If yes, it prints i and increases i by 1. When i reaches 3, the condition fails and the loop stops. The variable i changes from 0 to 3 over the loop. Key points are when the condition is checked and when i is updated. The loop runs exactly 3 times, printing i values 0, 1, and 2.