Next and break statements in R Programming - Time & Space Complexity
We want to see how using next and break affects how long a loop runs.
How do these statements change the number of steps the program takes?
Analyze the time complexity of the following code snippet.
for (i in 1:n) {
if (i %% 2 == 0) {
next # Skip even numbers
}
if (i > 10) {
break # Stop loop if i is greater than 10
}
print(i)
}
This code loops from 1 to n, skips even numbers, and stops when i is greater than 10.
Look at what repeats in the loop.
- Primary operation: Loop runs from 1 up to n, but may stop early.
- How many times: Up to 10 times because of the break statement.
The loop stops once i is greater than 10, so it never runs more than 10 times.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 (loop runs fully) |
| 10 | 10 (loop runs fully) |
| 100 | 10 (loop stops early) |
Pattern observation: The number of steps stays the same after n passes 10 because of the break.
Time Complexity: O(1)
This means the loop runs a fixed number of times, no matter how big n gets.
[X] Wrong: "The loop always runs n times even with break and next."
[OK] Correct: The break stops the loop early, so it may run fewer times than n.
Understanding how next and break affect loops helps you write efficient code and explain your logic clearly.
"What if we removed the break statement? How would the time complexity change?"