C++ Tutorial C++ Advanced C++ Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C++ - assignment operators example



The example below shows the usage of assignment and compound assignment operators:

  • = Assignment operator
  • += Addition AND assignment operator
  • -= Subtraction AND assignment operator
  • *= Multiply AND assignment operator
  • /= Division AND assignment operator
  • %= Modulo AND assignment operator
#include <iostream>
using namespace std;
 
int main (){
  float a = 25;

  cout<<"a = "<<a<<"\n";

  //Addition AND assignment operator
  a += 5;
  cout<<"a += 5; makes a = "<<a<<"\n";

  //Subtraction AND assignment operator
  a -= 8;
  cout<<"a -= 8; makes a = "<<a<<"\n";

  //Multiply AND assignment operator
  a *= 4;
  cout<<"a *= 4; makes a = "<<a<<"\n";

  //Division AND assignment operator
  a /= 2;
  cout<<"a /= 2; makes a = "<<a<<"\n";

  //Modulo AND assignment operator
  //works only with integral operands
  int b = 25;
  cout<<"\nb = "<<b<<"\n";
  b %= 7;
  cout<<"b %= 7; makes b = "<<b<<"\n";
  return 0;
}

The output of the above code will be:

a = 25
a += 5; makes a = 30
a -= 8; makes a = 22
a *= 4; makes a = 88
a /= 2; makes a = 44

b = 25
b %= 7; makes b = 4

❮ C++ - Operators

5