Scope of variables - Time & Space Complexity
Let's see how the time it takes to run code changes when we use variables in different places.
We want to know if where a variable is declared affects how long the program runs.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void example(int n) {
int i;
for (i = 0; i < n; i++) {
int temp = i * 2;
printf("%d\n", temp);
}
}
This code prints double the value of numbers from 0 to n-1, declaring a variable inside the loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 0 to n-1.
- How many times: The loop runs n times, and inside each loop, the variable
tempis declared and used.
Each time n grows, the loop runs more times, doing the same steps inside.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the loop runs |
| 100 | About 100 times the loop runs |
| 1000 | About 1000 times the loop runs |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time grows in a straight line with the input size n.
[X] Wrong: "Declaring a variable inside the loop makes the program slower because it creates the variable every time."
[OK] Correct: In C, declaring a variable inside the loop does not add extra time for creation each time; it just allocates space on the stack each iteration, which is part of the loop's work already counted.
Understanding how variable placement relates to time helps you write clear code without worrying about hidden slowdowns.
"What if we moved the variable temp declaration outside the loop? How would the time complexity change?"