0
0
C Sharp (C#)programming~5 mins

Assignment and compound assignment in C Sharp (C#) - Time & Space Complexity

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

Scenario Under Consideration

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.

Identify Repeating Operations

Look for repeated actions in the code.

  • Primary operation: The compound 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 times we add grows the same way.

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

Pattern observation: The work grows directly with n; double n means double the additions.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input size grows.

Common Mistake

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

Interview Connect

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

Self-Check

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