Assignment operators in C - Time & Space Complexity
Let's see how assignment operators affect the time it takes for a program to run.
We want to know how the number of assignments changes as the program runs with bigger inputs.
Analyze the time complexity of the following code snippet.
int sum = 0;
for (int i = 0; i < n; i++) {
sum += i; // assignment with addition
}
return sum;
This code adds numbers from 0 up to n-1 and stores the result in sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The 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 assignments grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The number of assignments grows in a straight line as n increases.
Time Complexity: O(n)
This means the time to complete the assignments grows directly with the size of the input.
[X] Wrong: "Assignment operations inside a loop don't affect time much because they are simple."
[OK] Correct: Even simple assignments add up when repeated many times, so they do affect total time.
Understanding how assignments inside loops affect time helps you explain code efficiency clearly and confidently.
"What if we replaced the assignment sum += i with a function call inside the loop? How would the time complexity change?"