Assignment Operators
& Compound Assignment Explained



Understanding Assignment Operators

At the heart of programming is the concept of storing and updating values. This is where the assignment operator comes into play. The most basic assignment operator is =.

It is used to assign the value on the right-hand side to the variable on the left-hand side.

Basic Assignment Example

x = 10

Here, the number 10 is stored in the variable x.

Output:

x contains 10

But what if we want to update the value?

Let’s say we want to increase the value of x by 5.

x = x + 5

This tells the program: “Take the current value of x, add 5 to it, and store the result back into x.”

Output:

x is now 15

What are Compound Assignment Operators?

To make such operations shorter and more readable, most programming languages support compound assignment operators.

Instead of writing x = x + 5, you can simply write:

x += 5

This means exactly the same thing: "Add 5 to x and store the result back in x."

List of Common Compound Assignment Operators

Operator Meaning Equivalent To
+= Add and assign x = x + value
-= Subtract and assign x = x - value
*= Multiply and assign x = x * value
/= Divide and assign x = x / value
%= Modulus and assign x = x % value

Example: Updating a Variable with Compound Assignment

count = 20
count -= 4
count *= 2

Step-by-step breakdown:

Output:

count is now 32

Question for Intuition

Q: What is the final value of score after the following operations?

score = 50
score += 25
score /= 5
score -= 2

A: Let’s solve it step-by-step:

Final Output:

score is 13

Why Use Compound Assignment?

Recap

The assignment operator (=) is used to store a value in a variable.

Compound assignment operators are shortcuts that combine arithmetic with assignment, like += or *=.

Understanding these not only makes your code shorter but also helps you think clearly about how values change during program execution.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M