For loop execution model in C Sharp (C#) - Time & Space Complexity
When we use a for loop, we want to know how the time it takes grows as we increase the number of times the loop runs.
We ask: How does the work inside the loop add up when the loop runs more times?
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++)
{
Console.WriteLine(i);
}
This code prints numbers from 0 up to n-1, running the loop n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and prints a number each time.
- How many times: Exactly n times, where n is the input size.
As n gets bigger, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with n; if n doubles, work doubles.
Time Complexity: O(n)
This means the time to finish 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: Printing still takes time each loop, so total time grows with n, no matter how simple the action is.
Understanding how loops grow with input size helps you explain code efficiency clearly and confidently in real situations.
"What if we added a nested loop inside this for loop? How would the time complexity change?"