0
0
Rustprogramming~10 mins

For loop in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop
Start
Get iterable
Take next item?
NoExit loop
Yes
Execute loop body
Repeat: Take next item?
The for loop gets an iterable, takes each item one by one, runs the loop body, and stops when no items remain.
Execution Sample
Rust
fn main() {
    for i in 1..4 {
        println!("{}", i);
    }
}
This code prints numbers 1, 2, and 3 using a for loop over a range.
Execution Table
Iterationi valueCondition (next item?)ActionOutput
11YesPrint 11
22YesPrint 22
33YesPrint 33
4-NoExit loop-
💡 No more items in range 1..4, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
i-123-
Key Moments - 2 Insights
Why does the loop stop after printing 3 and not include 4?
The range 1..4 in Rust includes 1, 2, and 3 but excludes 4, so the loop ends after 3 as shown in execution_table row 4.
What happens if the range is empty, like 5..5?
The loop never runs because there are no items to take, so the condition 'next item?' is No immediately, similar to execution_table row 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'i' at iteration 2?
A1
B3
C2
D-
💡 Hint
Check the 'i value' column in execution_table row 2
At which iteration does the loop condition become false?
AIteration 3
BIteration 4
CIteration 1
DNever
💡 Hint
Look at the 'Condition (next item?)' column in execution_table row 4
If the range changed to 1..3, how many times would the loop run?
A2 times
B1 time
C3 times
D0 times
💡 Hint
Ranges exclude the upper bound, so 1..3 includes 1 and 2 only, check variable_tracker for similar pattern
Concept Snapshot
Rust for loop syntax:
for variable in iterable {
    // code
}

Runs loop body once per item in iterable.
Ranges like 1..4 include start but exclude end.
Loop stops when no more items.
Full Transcript
This visual trace shows how a Rust for loop works by taking each item from an iterable one by one. The example uses a range 1..4 which includes 1, 2, and 3 but not 4. Each iteration assigns the current number to variable 'i' and prints it. The loop stops when there are no more items. The variable tracker shows how 'i' changes each iteration. Key moments clarify why 4 is excluded and what happens with empty ranges. The quiz tests understanding of iteration values and loop stopping conditions.