Assignment and compound assignment in C Sharp (C#) - Time & Space Complexity
Let's see how assignment and compound assignment affect the time a program takes to run.
We want to know how these operations grow when used in code.
Analyze the time complexity of the following code snippet.
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += i; // compound assignment
}
This code adds numbers from 0 up to n-1 using a compound assignment inside a loop.
Look for repeated actions in the code.
- Primary operation: The compound assignment
sum += iinside the loop. - How many times: It runs once for each number from 0 to n-1, so n times.
As n gets bigger, the number of times we add 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; double n means double the additions.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input size grows.
[X] Wrong: "Compound assignments are slower than simple assignments because they do more work."
[OK] Correct: Compound assignments combine operations but still run once per loop iteration, so their time grows the same way as simple assignments inside loops.
Understanding how simple operations inside loops affect time helps you explain code efficiency clearly and confidently.
What if we replaced the compound assignment sum += i with a method call inside the loop? How would the time complexity change?