Why C++ is widely used - Performance Analysis
We want to understand how the speed of C++ programs changes as the size of the input grows.
This helps us see why C++ is chosen for many tasks where performance matters.
Analyze the time complexity of a simple C++ loop that sums numbers.
int sum(int n) {
int total = 0;
for (int i = 1; i <= n; ++i) {
total += i;
}
return total;
}
This code adds all numbers from 1 to n and returns the total.
Look at what repeats in the code.
- Primary operation: Adding a number to total inside the loop.
- How many times: Exactly n times, once for each number from 1 to n.
As n gets bigger, 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; 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 runs faster because computers are fast, so time complexity does not matter."
[OK] Correct: Even fast computers take longer if the input grows a lot; understanding time complexity helps us predict and manage this growth.
Knowing how time grows with input size shows you understand why C++ is chosen for tasks needing speed and control.
"What if we replaced the loop with a formula that calculates the sum directly? How would the time complexity change?"