Labs ICT
โญ Pro Login

Operators

Operators let you work with values. The arithmetic operators are the ones you already know from math class โ€” addition, subtraction, multiplication, division, and modulo. C++ uses them the same way, just with a slightly different symbol for multiplication and modulo.

Arithmetic Operators

  • + โ€” addition
  • - โ€” subtraction
  • * โ€” multiplication
  • / โ€” division
  • % โ€” modulo (remainder of division)

One thing to watch out for โ€” when you divide two integers, C++ performs integer division. That means 7 / 2 gives you 3, not 3.5. If you want decimal results, make sure at least one of the values is a double or float.

#include <iostream>
using namespace std;

int main() {
  int a = 10, b = 3;

  cout << "a + b = " << (a + b) << endl;
  cout << "a - b = " << (a - b) << endl;
  cout << "a * b = " << (a * b) << endl;
  cout << "a / b = " << (a / b) << endl;
  cout << "a % b = " << (a % b) << endl;
  cout << "a / (double)b = " << (a / (double)b);
  return 0;
}

See the last line? By casting b to double, we get the decimal result 3.33333 instead of 3. We will talk more about type casting later.

๐Ÿงช Quick Quiz

What does the % operator do in C++?