Code chunks and output in R Programming - Time & Space Complexity
We want to see how the time to run code chunks grows as we add more lines or commands.
How does the number of code chunks affect the total work done?
Analyze the time complexity of the following code snippet.
# Print numbers from 1 to n
print_numbers <- function(n) {
for (i in 1:n) {
print(i)
}
}
print_numbers(5)
This code prints numbers from 1 up to n, one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each number.
- How many times: Exactly n times, once for each number.
As n grows, the number of print operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items printed.
[X] Wrong: "The code runs instantly no matter how big n is."
[OK] Correct: Each number must be printed one by one, so more numbers mean more time.
Understanding how loops affect time helps you explain code efficiency clearly and confidently.
"What if we changed the loop to print only every second number? How would the time complexity change?"