Introduction
Assignment operators help you store values in variables easily. They let you update or change values step by step.
Assignment operators help you store values in variables easily. They let you update or change values step by step.
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.
int x = 5;
x += 3; // same as x = x + 3;
x *= 2; // same as x = x * 2;
x %= 4; // same as x = x % 4;
This program shows how assignment operators change the value of x step by step.
#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; }
Assignment operators combine math and assignment in one step to save time.
Be careful with division and modulus to avoid dividing by zero.
Assignment operators store or update values in variables.
They make code shorter and easier to read.
Common ones include =, +=, -=, *=, /=, and %=.
+=+= adds the right side value to the left side variable and updates the variable with the new value.= assigns a value, -= subtracts, and *= multiplies. Only += adds and assigns.+= -> Option A+= [OK]x by 5 and store the result back in x?*=, so x *= 5; is correct.x =* 5; and x = 5*; are invalid syntax. x = 5 *; is incomplete.x *= 5; -> Option B*= [OK]int a = 10; a += 5; a -= 3; std::cout << a;
a += 5;a = 10, adding 5 gives a = 15.a -= 3;a = 12.int x = 7; x =+ 3; std::cout << x;
x =+ 3;+=. Instead, =+ means assign positive 3 to x.=+ is just assignment with unary plus.=+ is assignment, not addition [OK]int n = 20;, which code snippet correctly divides n by 4 and then subtracts 2 from the result, updating n accordingly?n by 4, then subtract 2 from the result, updating n each time.n /= 4; n -= 2; does n /= 4; then n -= 2;, matching the requirement. n -= 2; n /= 4; reverses order. n = (n - 2) / 4; subtracts first due to parentheses (18 / 4 = 4). n = n - 2 / 4; subtracts incorrectly.n /= 4; n -= 2; updates n stepwise as requested.n /= 4; n -= 2; [OK]Pass the test and this pattern moves unknown