The Big Master

Arithmetic assignment

Arithmetic assignment operators in C++ are used to perform an arithmetic operation...

Arithmetic assignment operators in C++ are used to perform an arithmetic operation and assign the result back to the same variable.

  1. Addition and Assignment (+=): Adds the value on the right side to the value on the left side and assigns the result to the left side variable. For example, x += y; is equivalent to x = x + y;.
  2. Subtraction and Assignment (-=): Subtracts the value on the right side from the value on the left side and assigns the result to the left side variable. For example, x -= y; is equivalent to x = x – y;.
  3. Multiplication and Assignment (*=): Multiplies the value on the right side with the value on the left side and assigns the result to the left side variable. For example, x *= y; is equivalent to x = x * y;.
  4. Division and Assignment (/=): Divides the value on the left side by the value on the right side and assigns the result to the left side variable. For example, x /= y; is equivalent to x = x / y;.
  5. Modulo and Assignment (%=): Performs modulo operation on the value on the left side with the value on the right side and assigns the result to the left side variable. For example, x %= y; is equivalent to x = x % y;.
#include <iostream>
using namespace std;

int main() {
    int x = 10;
    int y = 3;

    x += y;   // x is now 13 (10 + 3)
    x -= y;   // x is now 10 (13 - 3)
    x *= y;   // x is now 30 (10 * 3)
    x /= y;   // x is now 10 (30 / 3)
    x %= y;   // x is now 1  (10 % 3)

    cout << "Final x: " << x << endl;

    return 0;
}