0
0
Cprogramming~5 mins

Assignment operators in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Assignment operators
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The assignment sum += i inside the loop.
  • How many times: It runs once for each number from 0 to n-1, so n times.
How Execution Grows With Input

As n gets bigger, the number of assignments grows directly with n.

Input Size (n)Approx. Operations
1010 assignments
100100 assignments
10001000 assignments

Pattern observation: The number of assignments grows in a straight line as n increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the assignments grows directly with the size of the input.

Common Mistake

[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.

Interview Connect

Understanding how assignments inside loops affect time helps you explain code efficiency clearly and confidently.

Self-Check

"What if we replaced the assignment sum += i with a function call inside the loop? How would the time complexity change?"