Why loop control is required - Performance Analysis
Loops repeat actions many times, so how long a program takes depends a lot on them.
We want to see why controlling loops matters for how fast code runs.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
printf("%d\n", i);
}
This code prints numbers from 0 up to n-1 using a loop controlled by i.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs the print statement repeatedly.
- How many times: Exactly n times, controlled by the loop variable i.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
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 size of n.
[X] Wrong: "The loop will run forever if I don't control it."
[OK] Correct: Without proper control, the loop might never stop, causing the program to hang or crash.
Understanding loop control helps you write code that runs efficiently and avoids endless work, a key skill in programming.
"What if the loop condition changed from i < n to i < n*n? How would the time complexity change?"