Why loop control is required in Java - Performance Analysis
Loops repeat actions in code, so controlling them is important to avoid running forever.
We want to see how loop control affects how long the program runs as input grows.
Analyze the time complexity of the following code snippet.
int sum = 0;
for (int i = 0; i < n; i++) {
sum += i;
}
System.out.println(sum);
This code adds numbers from 0 up to n-1 and prints the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and adds numbers.
- How many times: Exactly n times, once for each number from 0 to n-1.
As n grows, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The loop will always stop quickly without control."
[OK] Correct: Without proper control, the loop might run forever, making the program freeze or crash.
Understanding loop control helps you write code that runs efficiently and safely, a key skill in many programming tasks.
"What if the loop condition was changed to i <= n instead of i < n? How would the time complexity change?"