For loop in Rust - Time & Space Complexity
We want to understand how the time it takes to run a for loop changes as the amount of data grows.
Specifically, how does the number of steps increase when the loop runs over more items?
Analyze the time complexity of the following code snippet.
fn sum_elements(numbers: &[i32]) -> i32 {
let mut total = 0;
for &num in numbers {
total += num;
}
total
}
This code adds up all the numbers in a list and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for loop that visits each number in the list.
- How many times: Once for every number in the input list.
As the list gets bigger, the loop runs more times, adding one step per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets longer.
[X] Wrong: "The loop runs a fixed number of times no matter the list size."
[OK] Correct: The loop actually runs once for each item, so bigger lists take more time.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave with more data.
"What if we replaced the for loop with two nested for loops over the same list? How would the time complexity change?"
Practice
for loop do in Rust?Solution
Step 1: Understand the purpose of a for loop
A for loop runs code repeatedly for each item in a list or range.Step 2: Match the description to the options
Only Repeats actions for each item in a collection describes repeating actions over items in a collection.Final Answer:
Repeats actions for each item in a collection -> Option CQuick Check:
For loop = repeat over items [OK]
- Confusing for loop with function definition
- Thinking for loop declares variables
- Believing for loop stops program
Solution
Step 1: Recall Rust for loop syntax
Rust usesfor variable in range { }with ranges like1..=3to include 3.Step 2: Check each option
for i in 1..=3 { println!("{}", i); } uses correct Rust syntax with inclusive range. Others use invalid syntax or functions not in Rust.Final Answer:
for i in 1..=3 { println!("{}", i); } -> Option BQuick Check:
Rust for loop usesinand ranges [OK]
- Using 'to' instead of 'in' keyword
- Using parentheses around loop variable
- Using Python or other language range syntax
let mut sum = 0;
for i in 1..4 {
sum += i;
}
println!("{}", sum);Solution
Step 1: Identify the loop range and iterations
The loop runs for i = 1, 2, 3 because 1..4 excludes 4.Step 2: Calculate the sum of iterations
sum = 0 + 1 + 2 + 3 = 6Final Answer:
6 -> Option AQuick Check:
1+2+3 = 6 [OK]
- Including 4 in the sum
- Starting sum at 1 instead of 0
- Confusing inclusive and exclusive ranges
for i in 0..5
println!("{}", i);
}Solution
Step 1: Check loop syntax
Rust requires curly braces { } around the loop body if it has more than one statement or to be explicit.Step 2: Identify the missing brace
The code has a closing brace '}' without an opening brace '{' before println!().Final Answer:
Missing curly braces around loop body -> Option DQuick Check:
For loop body needs braces [OK]
- Forgetting opening brace
- Assuming range syntax is wrong
- Thinking variable needs declaration outside loop
Solution
Step 1: Understand the range and condition
We want numbers from 2 to 10 inclusive, so use 2..=10. To print even numbers, check if remainder when divided by 2 is zero.Step 2: Check each option's condition
for i in 2..=10 { if i % 2 == 0 { println!("{}", i); } } correctly usesi % 2 == 0. for i in 2..10 { if i % 2 = 0 { println!("{}", i); } } uses assignment (=) instead of comparison (==). for i in 2..=10 { if i / 2 == 0 { println!("{}", i); } } uses division instead of modulo. for i in 2..=10 { if i % 2 != 0 { println!("{}", i); } } prints odd numbers.Final Answer:
for i in 2..=10 { if i % 2 == 0 { println!("{}", i); } } -> Option AQuick Check:
Use modulo == 0 for even check [OK]
- Using '=' instead of '==' in condition
- Using division instead of modulo
- Printing odd numbers by mistake
Ready to prove it?
Pass the test and this pattern moves unknown
