While loop execution model in C Sharp (C#) - Time & Space Complexity
We want to understand how the time a while loop takes changes as the input grows.
Specifically, how many times the loop runs affects the total work done.
Analyze the time complexity of the following code snippet.
int i = 0;
while (i < n)
{
Console.WriteLine(i);
i++;
}
This code prints numbers from 0 up to n-1 using a while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs and prints a number each time.
- How many times: It runs once for each number from 0 to n-1, so n times.
As n grows, 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; doubling n doubles the work.
Time Complexity: O(n)
This means the time taken grows in a straight line with the size of n.
[X] Wrong: "The while loop runs a fixed number of times no matter what n is."
[OK] Correct: The loop runs once for each number up to n, so if n grows, the loop runs more times.
Understanding how loops grow with input size helps you explain your code clearly and shows you can think about efficiency.
"What if we changed the loop to increase i by 2 each time? How would the time complexity change?"