0
0
C Sharp (C#)programming~5 mins

Do-while loop execution model in C Sharp (C#) - Time & Space Complexity

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

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

How many times does the loop run when the input gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int i = 0;
do
{
    Console.WriteLine(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 loop runs more times, directly matching n.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The number of operations grows in a straight line with n.

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows directly in proportion to the input size.

Common Mistake

[X] Wrong: "A do-while loop always runs at least twice, so it has constant time."

[OK] Correct: The do-while loop runs at least once, but the total runs depend on n, so time grows with input size.

Interview Connect

Understanding how loops like do-while behave helps you explain how your code scales, a key skill in programming.

Self-Check

"What if the loop condition changed to run while i <= n? How would the time complexity change?"