Assignment operators are used to assign a value to a variable in C++. These operators include simple assignment (=), as well as compound assignment operators like +=, -=, *=, /=, and %= which combine an arithmetic operator and assignment into a single operation.
Here are some examples of how to use these operators:
The simple assignment operator is used to assign a value to a variable. Here's an example:
int a;
a = 10; // a now has the value of 10The addition assignment operator is used to add a value to a variable and assign the result to the variable. Here's an example:
int a = 10;
a += 5; // a now has the value of 15This is equivalent to writing a = a + 5.
The subtraction assignment operator is used to subtract a value from a variable and assign the result to the variable. Here's an example:
int a = 10;
a -= 5; // a now has the value of 5This is equivalent to writing a = a - 5.
The multiplication assignment operator is used to multiply a variable by a value and assign the result to the variable. Here's an example:
int a = 10;
a *= 5; // a now has the value of 50This is equivalent to writing a = a * 5.
The division assignment operator is used to divide a variable by a value and assign the result to the variable. Here's an example:
int a = 10;
a /= 5; // a now has the value of 2This is equivalent to writing a = a / 5.
The modulus assignment operator is used to take the modulus of a variable by a value and assign the result to the variable. Here's an example:
int a = 10;
a %= 3; // a now has the value of 1This is equivalent to writing a = a % 3.
I hope this helps you to understand assignment operators in C++!