For loop in C - Time & Space Complexity
We want to understand how the time a for loop takes changes as we increase the number of times it runs.
How does the work grow when the loop runs more times?
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
printf("%d\n", i);
}
This code prints numbers from 0 up to n-1 using a for loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for loop runs the print statement.
- How many times: Exactly n times, once for each number from 0 to n-1.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The work grows directly with n. Double n, double the work.
Time Complexity: O(n)
This means the time grows in a straight line with the number of loop runs.
[X] Wrong: "The loop runs faster because it just prints numbers quickly."
[OK] Correct: The speed of printing does not change how many times the loop runs. The loop still runs n times, so time grows with n.
Understanding how loops affect time helps you explain how your code scales and shows you can think about efficiency clearly.
"What if we added a second nested for loop inside this one? How would the time complexity change?"