Why variables are needed in Rust - Performance Analysis
We want to understand how using variables affects the steps a program takes.
How does storing and reusing values change the work done as the program runs?
Analyze the time complexity of the following code snippet.
fn sum_first_n(n: u32) -> u32 {
let mut sum = 0;
for i in 1..=n {
sum += i;
}
sum
}
This code adds numbers from 1 to n using a variable to keep the running total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds each number to the sum variable.
- How many times: The loop runs n times, once for each number from 1 to n.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the program takes longer in a straight line as the input number gets bigger.
[X] Wrong: "Using a variable makes the program run faster or slower by itself."
[OK] Correct: Variables just hold values; the time depends on how many times we use them, not on having them.
Understanding how variables affect steps helps you explain your code clearly and shows you know how programs grow with input size.
"What if we replaced the for-loop with a formula that calculates the sum directly? How would the time complexity change?"