Why loop control is required in C++ - Performance Analysis
Loops repeat actions in code, but without control, they can run too long or forever.
We want to see how controlling loops affects how long a program runs.
Analyze the time complexity of the following code snippet.
int i = 0;
while (i < 5) {
std::cout << i << std::endl;
i++;
}
This code prints numbers from 0 to 4 by increasing i each time until it reaches 5.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs repeatedly.
- How many times: It runs 5 times, controlled by the variable i.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 times |
| 10 | 10 times |
| 100 | 100 times |
Pattern observation: The number of loop runs grows directly with the input number controlling it.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the loop count increases.
[X] Wrong: "The loop will always stop on its own without control."
[OK] Correct: Without a condition that changes, the loop can run forever, making the program stuck.
Understanding loop control shows you can write code that runs efficiently and safely without getting stuck.
"What if we forgot to increase i inside the loop? How would the time complexity change?"