Continue statement in Java - Time & Space Complexity
Let's see how using the continue statement affects the time complexity of a loop.
We want to know how the number of steps changes as the input grows.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
This code loops from 0 to n-1, skips even numbers using continue, and prints only 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 print happens only for about half of them.
As n grows, the loop runs more times, but continue skips some steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop checks, 5 prints |
| 100 | 100 loop checks, 50 prints |
| 1000 | 1000 loop checks, 500 prints |
Pattern observation: The loop runs n times, but the print runs about n/2 times. The continue skips printing for half the cases.
Time Complexity: O(n)
This means the total steps grow linearly with the input size, even with continue skipping some steps.
[X] Wrong: "Using continue makes the loop run faster and reduces time complexity."
[OK] Correct: Continue only skips some steps inside the loop but the loop still runs n times, so the overall time grows linearly with n.
Understanding how continue affects loops helps you explain code behavior clearly and shows you can analyze performance carefully.
"What if we replaced continue with a nested if statement that only prints when i is odd? How would the time complexity change?"