Continue statement in C++ - Time & Space Complexity
We want to see how using the continue statement affects how long a program takes to run.
Specifically, does skipping some steps change the overall work done as input 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 work here
int x = i * 2;
}
This code loops through numbers from 0 to n-1, skipping even numbers using continue.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 0 to n-1.
- How many times: It runs n times, but the work inside after
continueruns only for odd i values.
As n grows, the loop runs n times, but the work after continue happens only about 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 runs grow linearly with n, and the work inside grows roughly half as fast.
Time Complexity: O(n)
This means the program's running time grows in a straight line as the input size increases, even with the continue skipping some steps.
[X] Wrong: "Using continue makes the loop run faster and changes the time complexity to less than linear."
[OK] Correct: The loop still runs n times; skipping some steps only reduces work by a constant factor, not the overall growth pattern.
Understanding how control statements like continue affect time helps you explain your code clearly and reason about efficiency in real projects.
"What if the continue condition depended on a nested loop? How would that change the time complexity?"