0
0
R Programmingprogramming~5 mins

Why control flow directs execution in R Programming - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why control flow directs execution
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time n grows, the loop runs more times, doing one check and one print per number.

Input Size (n)Approx. Operations
10About 10 checks and 10 prints
100About 100 checks and 100 prints
1000About 1000 checks and 1000 prints

Pattern observation: The work grows directly with n, doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we added a nested loop inside the if block? How would the time complexity change?"