0
0
R Programmingprogramming~5 mins

While loop in R Programming - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: While loop
O(n)
Understanding Time Complexity

We want to understand how the time a while loop takes changes as the input grows.

Specifically, how many times does the loop run when the input gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


i <- 1
while (i <= n) {
  print(i)
  i <- i + 1
}
    

This code prints numbers from 1 up to n using a while loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs and prints a number each time.
  • How many times: It runs once for each number from 1 to n, so n times.
How Execution Grows With Input

As n grows, the number of times the loop runs grows the same way.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line with the size of n.

Common Mistake

[X] Wrong: "The while loop runs a fixed number of times no matter what n is."

[OK] Correct: The loop depends on n, so if n gets bigger, the loop runs more times.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how to write efficient programs.

Self-Check

"What if we changed the loop to increase i by 2 each time? How would the time complexity change?"