Do-while loop execution model in C Sharp (C#) - Time & Space Complexity
We want to understand how the time a do-while loop takes changes as the input size grows.
How many times does the loop run when the input gets bigger?
Analyze the time complexity of the following code snippet.
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < n);
This code prints numbers from 0 up to n-1 using a do-while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The do-while loop runs the print statement repeatedly.
- How many times: It runs exactly n times, once for each number from 0 to n-1.
As n grows, the loop runs more times, directly matching n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows in a straight line with n.
Time Complexity: O(n)
This means the time taken grows directly in proportion to the input size.
[X] Wrong: "A do-while loop always runs at least twice, so it has constant time."
[OK] Correct: The do-while loop runs at least once, but the total runs depend on n, so time grows with input size.
Understanding how loops like do-while behave helps you explain how your code scales, a key skill in programming.
"What if the loop condition changed to run while i <= n? How would the time complexity change?"