Increment and decrement operators in C++ - Time & Space Complexity
We want to see how the time it takes to run code with increment and decrement operators changes as the input size grows.
Specifically, we ask: how many times do these operators run when used inside loops?
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
// increment operator used in loop control
// some constant time operation
}
This code runs a loop from 0 up to n, increasing i by 1 each time using the increment operator.
- Primary operation: The increment operator
i++inside the loop control. - How many times: It runs once each loop iteration, so about n times.
As n grows, the number of times the increment operator runs grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 increments |
| 100 | About 100 increments |
| 1000 | About 1000 increments |
Pattern observation: The work grows in a straight line as input size increases.
Time Complexity: O(n)
This means the time to run the code grows directly in proportion to the size of the input.
[X] Wrong: "Increment operators inside loops run only once regardless of loop size."
[OK] Correct: The increment operator runs every time the loop repeats, so it runs as many times as the loop runs, not just once.
Understanding how simple operations like increments add up helps you explain how loops affect performance clearly and confidently.
"What if we changed the increment operator to decrement and looped down from n to 0? How would the time complexity change?"