Why functions organize code in R Programming - Performance Analysis
When we use functions, we group code into reusable parts. This helps keep things neat and clear.
We want to see how using functions affects how long the program takes to run.
Analyze the time complexity of the following code snippet.
# Function to add numbers from 1 to n
sum_numbers <- function(n) {
total <- 0
for (i in 1:n) {
total <- total + i
}
return(total)
}
result <- sum_numbers(100)
print(result)
This code defines a function that adds numbers from 1 up to n, then calls it with 100.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop adding numbers from 1 to n.
- How many times: It runs exactly n times, once for each number.
As n gets bigger, the loop runs more times, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps 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 size of the input.
[X] Wrong: "Using a function makes the code run faster automatically."
[OK] Correct: Functions help organize code but do not change how many steps the program takes.
Understanding how functions affect time helps you write clear code without surprises about speed.
"What if the function called itself recursively instead of using a loop? How would the time complexity change?"