Why control flow directs execution in R Programming - Performance Analysis
Control flow decides which parts of code run and how often. This affects how long a program takes to finish.
We want to see how the program's steps grow as input changes.
Analyze the time complexity of the following code snippet.
for (i in 1:n) {
if (i %% 2 == 0) {
print(i)
} else {
print(i * 2)
}
}
This code runs a loop from 1 to n and uses an if-else to decide what to print each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs through numbers 1 to n.
- How many times: Exactly n times, once for each number.
Each time n grows, the loop runs more times, doing one check and one print per number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and 10 prints |
| 100 | About 100 checks and 100 prints |
| 1000 | About 1000 checks and 1000 prints |
Pattern observation: The work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "The if-else makes the code run twice as long because it has two paths."
[OK] Correct: Only one path runs each time, so the total steps still match the loop count.
Understanding how control flow affects steps helps you explain code speed clearly. This skill shows you can think about program behavior beyond just writing code.
"What if we added a nested loop inside the if block? How would the time complexity change?"