Assignment and increment operators are used to assign values to variables and modify them efficiently. They are essential in loops, calculations, and program logic. These operators make programming easier by combining operations with assignment.
Assignment Operators
Assignment operators are used to store values in variables. The simplest assignment operator is =. Other assignment operators combine arithmetic operations with assignment, such as += and -=.
The Basic Assignment Operator (=)
The
=operator assigns a value on the right-hand side to a variable on the left-hand side.
Output:
Here,
10is assigned to variablea.
Compound Assignment Operators (+=, -=)
These operators perform an arithmetic operation and assignment in one step.
Using += (Addition Assignment)
a += bis equivalent toa = a + b.
Output:
Saves typing and makes code cleaner.
Using -= (Subtraction Assignment)
a -= bis equivalent toa = a - b.
Output:
Similar operators exist for multiplication and division:
*=→a *= b(a = a * b)/=→a /= b(a = a / b)%=→a %= b(a = a % b)
Advantages of Assignment Operators
Simplifies code – fewer characters to type.
Avoids repetition – no need to write variable name twice.
Useful in loops – e.g., accumulating a sum:
Output:
Increment and Decrement Operators
Increment (++) and decrement (--) operators are used to increase or decrease a variable by 1. They are very common in loops and counters.
Increment Operator (++)
Syntax:
++variable(pre-increment) orvariable++(post-increment)Increases the value of the variable by 1.
Pre-increment (++variable)
The variable is incremented first, then used in the expression.
Output:
Post-increment (variable++)
The variable is used first, then incremented.
Output:
Decrement Operator (--)
Decreases the value of a variable by 1.
Pre-decrement:
--variable→ decrements first, then uses the valuePost-decrement:
variable--→ uses the value first, then decrements
Output:
Using Increment/Decrement in Loops
Very common in for loops to control the loop counter.
Here,
i++incrementsiafter each iteration.You can also count backwards using
--:
Output:
Combining Assignment and Increment Operators
Increment can also be combined with assignment:
This is functionally similar to
a++but more readable in some contexts.