Repeat loop with break in R Programming - Time & Space Complexity
We want to understand how long a repeat loop with a break runs as the input size changes.
Specifically, how many times does the loop repeat before it stops?
Analyze the time complexity of the following code snippet.
i <- 1
repeat {
if (i > n) {
break
}
print(i)
i <- i + 1
}
This code counts from 1 up to n, printing each number, then stops.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The repeat loop that prints numbers.
- How many times: It runs once for each number from 1 to n, so n times.
As n gets bigger, the loop runs more times, directly matching n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 repeats |
| 100 | About 100 repeats |
| 1000 | About 1000 repeats |
Pattern observation: The number of repeats grows evenly as n grows.
Time Complexity: O(n)
This means the time to finish grows directly with the size of n.
[X] Wrong: "The repeat loop always runs forever because it has no set end."
[OK] Correct: The break condition stops the loop once i passes n, so it does end after n repeats.
Understanding how loops with breaks behave helps you explain how code runs step-by-step and how long it takes.
"What if the break condition checked for i > n^2 instead? How would the time complexity change?"