Continue statement - Time & Space Complexity
Let's see how the continue statement affects the time complexity of a loop in C.
We want to know how the number of steps changes as the input size grows.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
continue;
}
// Some constant time operation
sum += i;
}
This code loops from 0 to n-1, skips even numbers using continue, and sums odd numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 0 to n-1.
- How many times: The loop runs n times, but the sum operation runs only for odd i values (about n/2 times).
Even though some steps are skipped, the loop still checks every number up to n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop checks, ~5 sum operations |
| 100 | 100 loop checks, ~50 sum operations |
| 1000 | 1000 loop checks, ~500 sum operations |
Pattern observation: The total steps grow roughly in a straight line as n grows.
Time Complexity: O(n)
This means the time to run the loop grows directly with the size of n, even with the continue skipping some steps.
[X] Wrong: "Since continue skips some steps, the loop runs faster and time complexity is less than O(n)."
[OK] Correct: The loop still checks every number once, so the total steps still grow with n. Skipping inside the loop does not reduce the number of loop iterations.
Understanding how control statements like continue affect loops helps you explain code efficiency clearly and confidently in interviews.
What if we replaced the continue with a nested loop inside the if-block? How would the time complexity change?