0
0
Javaprogramming~5 mins

Counter-based while loop in Java - Time & Space Complexity

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

We want to see how the time it takes to run a counter-based while loop changes as the number it counts to gets bigger.

How does the number of steps grow when the loop runs more times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int count = 0;
while (count < n) {
    System.out.println(count);
    count++;
}
    

This code prints numbers from 0 up to n-1 using a while loop that increases the counter each time.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs and prints the current count.
  • How many times: It repeats exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

As n gets bigger, the loop runs more times, so the total steps grow in a straight line with n.

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

Pattern observation: Doubling n doubles the work, so the growth is steady and linear.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly in proportion to the size of n.

Common Mistake

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

[OK] Correct: The loop depends on n and runs once for each number up to n, so bigger n means more steps.

Interview Connect

Understanding how loops grow with input size is a key skill. It helps you explain how your code will behave with bigger data, which is important in many real tasks.

Self-Check

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