Loop construct in Rust - Time & Space Complexity
Loops are a basic way to repeat actions in code. Understanding how loops affect time helps us know how fast or slow a program runs as input grows.
We want to see how the number of steps changes when the loop runs more times.
Analyze the time complexity of the following code snippet.
fn sum_numbers(numbers: &[i32]) -> i32 {
let mut total = 0;
for &num in numbers {
total += num;
}
total
}
This code adds up all numbers in a list and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to the total inside the for-loop.
- How many times: Once for every number in the input list.
Each number in the list causes one addition. So, if the list gets bigger, the work grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the input size.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items.
[X] Wrong: "The loop runs only once, so time is constant."
[OK] Correct: The loop runs once for each item, so more items mean more work, not just one step.
Knowing how loops affect time helps you explain your code clearly and shows you understand how programs grow with input size.
"What if we used two nested loops over the same list? How would the time complexity change?"
Practice
loop keyword do in Rust?Solution
Step 1: Understand the
Theloopkeywordloopkeyword in Rust creates a loop that repeats forever unless stopped.Step 2: Identify how to stop the loop
To stop aloop, you must usebreakinside it; otherwise, it runs infinitely.Final Answer:
It creates an infinite loop that runs untilbreakis called. -> Option BQuick Check:
loop= infinite loop until break [OK]
loop runs forever unless broken [OK]- Thinking
loopruns a fixed number of times - Confusing
loopwithfororwhile - Assuming
loopstops automatically
Solution
Step 1: Check Rust syntax for infinite loops
Rust uses the keywordloopto create an infinite loop.Step 2: Verify each option
while True { println!("Hello"); }useswhile Truewhich is invalid syntax in Rust.for i in 0.. { println!("Hello"); }usesforwith an infinite range, but0..is not valid without an end.repeat { println!("Hello"); }usesrepeatwhich does not exist in Rust.loop { println!("Hello"); }correctly usesloop.Final Answer:
loop { println!("Hello"); } -> Option AQuick Check:
Correct infinite loop syntax =loop[OK]
loop keyword for infinite loops in Rust [OK]- Using
while Truewhich is invalid in Rust - Trying to use
repeatwhich doesn't exist - Using
forwithout a proper range
let mut count = 0;
loop {
count += 1;
if count == 3 {
break;
}
println!("{}", count);
}Solution
Step 1: Trace the loop iterations
Initially, count = 0. In the first loop, count becomes 1, which is printed. Then count becomes 2 and printed. When count becomes 3, the loop breaks before printing.Step 2: List printed values
Only 1 and 2 are printed before the break stops the loop.Final Answer:
1 2 -> Option AQuick Check:
Loop prints until count == 3, so prints 1 and 2 [OK]
- Printing count after break condition
- Starting count from 0 but expecting 0 to print
- Assuming infinite loop without break
let mut i = 0;
loop {
if i == 5 {
break;
}
println!("{}", i);
}Solution
Step 1: Check loop control variable
The variableiis initialized but never changed inside the loop.Step 2: Understand loop behavior
Sinceinever increments,i == 5is never true, sobreakis never reached, causing an infinite loop.Final Answer:
Variable 'i' is not incremented, causing an infinite loop. -> Option DQuick Check:
Loop needs variable increment to reach break [OK]
- Forgetting to increment loop variable
- Assuming break works without condition change
- Misunderstanding loop syntax
loop to sum numbers from 1 to 5 in Rust?Solution
Step 1: Plan the loop with counter and sum
Initialize a counter at 1 and sum at 0. Useloopto add counter to sum.Step 2: Use
Increment counter each loop. When counter > 5, usebreakto stop after 5breakto exit loop.Step 3: Result is sum of 1 to 5
This method correctly sums numbers 1+2+3+4+5 = 15.Final Answer:
Use aloopwith a counter andbreakwhen counter > 5, adding each to sum. -> Option CQuick Check:
Loop + counter + break = sum 1 to 5 [OK]
- Not breaking loop causing infinite sum
- Not incrementing counter
- Not adding counter to sum
Ready to prove it?
Pass the test and this pattern moves unknown
