The single equals sign = means 'store this value'.
Compound assignments like += mean 'add and store', so x += 3 is like x = x + 3.
Examples
This sets x first to 5, then changes it to 10.
C Sharp (C#)
int x = 5;
x = 10;
This adds 3 to x, so x becomes 8.
C Sharp (C#)
int x = 5;
x += 3;
This subtracts 4 from x, so x becomes 6.
C Sharp (C#)
int x = 10;
x -= 4;
This multiplies x by 4, so x becomes 12.
C Sharp (C#)
int x = 3;
x *= 4;
Sample Program
This program shows how to use assignment and compound assignment to change the value of score. It prints the value after each change so you can see how it updates.
C Sharp (C#)
using System;
class Program
{
staticvoid Main()
{
int score = 10;
Console.WriteLine($"Initial score: {score}");
score += 5; // Add 5
Console.WriteLine($"After adding 5: {score}");
score -= 3; // Subtract 3
Console.WriteLine($"After subtracting 3: {score}");
score *= 2; // Multiply by 2
Console.WriteLine($"After multiplying by 2: {score}");
score /= 4; // Divide by 4
Console.WriteLine($"After dividing by 4: {score}");
score %= 3; // Remainder after dividing by 3
Console.WriteLine($"After modulo 3: {score}");
}
}
OutputSuccess
Important Notes
Compound assignments save time and make code easier to read.
Be careful with division and modulo to avoid dividing by zero.
Summary
Use = to store a value in a variable.
Use compound assignments like +=, -=, *= to update values quickly.
Compound assignments combine an operation and assignment in one step.
Practice
(1/5)
1. What does the compound assignment operator += do in C#?
easy
A. Multiplies the left variable by the right value
B. Subtracts the right value from the left variable
C. Adds the right value to the left variable and assigns the result to the left variable
D. Divides the left variable by the right value
Solution
Step 1: Understand the operator meaning
The += operator adds the right side value to the left side variable.
Step 2: Assign the result back
The result of the addition is stored back into the left variable.
Final Answer:
Adds the right value to the left variable and assigns the result to the left variable -> Option C
Quick Check:
+= means add and assign [OK]
Hint: Remember: += means add then assign in one step [OK]
Common Mistakes:
Confusing += with subtraction or multiplication
Thinking += just adds without assignment
Using += on constants (which is invalid)
2. Which of the following is the correct syntax to multiply a variable x by 5 using a compound assignment in C#?