⬅ Previous Topic
Logical Operators - AND, OR, NOTNext Topic ⮕
Bitwise Operators - AND, OR, XOR, NOT⬅ Previous Topic
Logical Operators - AND, OR, NOTNext Topic ⮕
Bitwise Operators - AND, OR, XOR, NOTAt 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.
x = 10
Here, the number 10
is stored in the variable x
.
Output:
x contains 10
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
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
."
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 |
count = 20
count -= 4
count *= 2
Step-by-step breakdown:
count = 20
count -= 4
subtracts 4 → count becomes 16count *= 2
multiplies by 2 → count becomes 32Output:
count is now 32
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:
score = 50
score += 25
→ 75score /= 5
→ 15score -= 2
→ 13Final Output:
score is 13
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.
⬅ Previous Topic
Logical Operators - AND, OR, NOTNext Topic ⮕
Bitwise Operators - AND, OR, XOR, NOTYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.