Continue statement behavior in C Sharp (C#) - Time & Space Complexity
Let's see how the continue statement affects the time it takes for a loop to run.
We want to know how skipping some steps changes the total work done.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++)
{
if (i % 2 == 0)
continue;
// Some constant time work here
Console.WriteLine(i);
}
This code loops from 0 to n-1 but skips the loop body when the number is even.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs from 0 to n-1.
- How many times: The loop runs n times, but the body runs only for odd numbers, about n/2 times.
Even though the loop runs n times, the work inside the loop happens only half the time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop checks, 5 work executions |
| 100 | 100 loop checks, 50 work executions |
| 1000 | 1000 loop checks, 500 work executions |
Pattern observation: The total loop steps grow linearly with n, and the work inside grows roughly half as fast.
Time Complexity: O(n)
This means the total time grows in a straight line as the input size increases, even with the continue skipping some steps.
[X] Wrong: "Because continue skips half the work, the time complexity is O(n/2) or less."
[OK] Correct: We ignore that the loop still runs n times, so the total steps still grow linearly with n. Constants like 1/2 do not change the overall growth type.
Understanding how skipping steps affects loops helps you explain code efficiency clearly and confidently in interviews.
What if we changed the continue condition to skip every third iteration instead of every even one? How would the time complexity change?