0
0
Javaprogramming~5 mins

Why loops are needed in Java - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why loops are needed
O(n)
Understanding Time Complexity

Loops help us repeat actions many times without writing the same code again and again.

We want to see how the time to run code changes when we use loops.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for (int i = 0; i < n; i++) {
    System.out.println(i);
}
    

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

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Printing a number inside the loop.
  • How many times: Exactly n times, once for each number from 0 to n-1.
How Execution Grows With Input

As n grows, the number of print actions grows the same way.

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

Pattern observation: The work grows directly with n; double n means double the prints.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "The loop runs only once no matter the input size."

[OK] Correct: The loop runs once for each number up to n, so more input means more repeats.

Interview Connect

Understanding loops and their time cost helps you explain how programs handle repeated tasks efficiently.

Self-Check

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