Auto storage class - Time & Space Complexity
Let's see how the auto storage class affects the time complexity of a simple function.
We want to know how the number of operations changes as input size grows.
Analyze the time complexity of the following code snippet.
void printNumbers(int n) {
auto int i; // auto is default for local variables
for (i = 0; i < n; i++) {
printf("%d\n", i);
}
}
This code prints numbers from 0 up to n-1 using an auto variable inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints numbers.
- How many times: It runs exactly n times.
As n grows, the loop runs more times, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prints |
| 100 | About 100 prints |
| 1000 | About 1000 prints |
Pattern observation: The work increases steadily as n increases.
Time Complexity: O(n)
This means the time to run grows in direct proportion to the input size n.
[X] Wrong: "Using the auto keyword changes how fast the code runs."
[OK] Correct: The auto keyword just means the variable is local and automatic; it does not affect how many times the loop runs or the overall time complexity.
Understanding how local variables and loops affect time helps you explain code efficiency clearly and confidently.
"What if we replaced the for-loop with a nested loop running n times inside another loop running n times? How would the time complexity change?"