Why loops are needed in C++ - Performance Analysis
Loops help us repeat actions many times without writing the same code again and again.
We want to know how the time to run the code changes when we repeat tasks more times.
Analyze the time complexity of the following code snippet.
int sum = 0;
for (int i = 0; i < n; i++) {
sum += i;
}
return sum;
This code adds numbers from 0 up to n-1 and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding a number to sum inside the loop.
- How many times: The loop runs n times, once for each number from 0 to n-1.
Each time n gets bigger, the loop runs more times, so the work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: When n doubles, the work doubles too.
Time Complexity: O(n)
This means the time to finish grows directly with the number of times we repeat the loop.
[X] Wrong: "The loop runs only once, so it takes constant time."
[OK] Correct: The loop runs n times, so the time depends on n, not just once.
Understanding how loops affect time helps you explain how your code handles bigger tasks clearly and confidently.
"What if we added a second nested loop inside the first? How would the time complexity change?"