0
0
Cprogramming~5 mins

Do–while loop in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Do-while loop
O(n)
Understanding Time Complexity

Let's see how the time taken by a do-while loop changes as the input size grows.

We want to know how many times the loop runs when the input gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int i = 0;
do {
    printf("%d\n", i);
    i++;
} while (i < n);
    

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

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The do-while loop runs the print statement repeatedly.
  • How many times: It runs exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

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

Input Size (n)Approx. Operations
1010 times
100100 times
10001000 times

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

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the input size; more input means more loop runs.

Common Mistake

[X] Wrong: "The do-while loop runs one extra time compared to a while loop, so it takes more time."

[OK] Correct: Both loops run roughly the same number of times based on n; the difference is only in when the condition is checked, not the total count for this case.

Interview Connect

Understanding how loops grow with input size helps you explain your code clearly and shows you know how to think about efficiency.

Self-Check

"What if we changed the loop to count down from n to 0? How would the time complexity change?"