0
0
C++programming~5 mins

Assignment operators in C++

Choose your learning style9 modes available
Introduction

Assignment operators help you store values in variables easily. They let you update or change values step by step.

When you want to save a number or text into a variable.
When you want to add or subtract a value from a variable quickly.
When you want to multiply or divide a variable by a number and save the result.
When you want to update a variable based on its current value.
Syntax
C++
variable = value;
variable += value;
variable -= value;
variable *= value;
variable /= value;
variable %= value;

The = operator sets the variable to a new value.

The other operators like += add and assign in one step.

Examples
Assign 5 to variable x.
C++
int x = 5;
Add 3 to x and save the result back to x.
C++
x += 3;  // same as x = x + 3;
Multiply x by 2 and save the result back to x.
C++
x *= 2;  // same as x = x * 2;
Set x to the remainder when x is divided by 4.
C++
x %= 4;  // same as x = x % 4;
Sample Program

This program shows how assignment operators change the value of x step by step.

C++
#include <iostream>

int main() {
    int x = 10;
    std::cout << "Initial x: " << x << "\n";

    x += 5;
    std::cout << "After x += 5: " << x << "\n";

    x -= 3;
    std::cout << "After x -= 3: " << x << "\n";

    x *= 2;
    std::cout << "After x *= 2: " << x << "\n";

    x /= 4;
    std::cout << "After x /= 4: " << x << "\n";

    x %= 3;
    std::cout << "After x %= 3: " << x << "\n";

    return 0;
}
OutputSuccess
Important Notes

Assignment operators combine math and assignment in one step to save time.

Be careful with division and modulus to avoid dividing by zero.

Summary

Assignment operators store or update values in variables.

They make code shorter and easier to read.

Common ones include =, +=, -=, *=, /=, and %=.