Operators

Programming Languages · C++ Basics · 10 min

Do maths with variables, split things up with / and %, and compare values.

Doing maths

C++ is a great calculator. + adds, - subtracts, * multiplies and / divides. It works on variables too:

int x = 6;
int y = 2;
std::cout << x - y << "\n";   // 4
  • Print a + b.

  • On the next line, print a * b.

Whole-number division

When both numbers are int, / throws away the leftover part: 7 / 2 is 3, not 3.5. The % operator (called modulo) gives you that leftover:

std::cout << 7 / 2 << "\n";    // 3
std::cout << 7 % 2 << "\n";    // 1
std::cout << 7.0 / 2 << "\n";  // 3.5, a double keeps decimals
  • Print how many cookies each kid gets: cookies / kids.

  • On the next line, print how many are left over: cookies % kids.

Shortcuts: += and ++

Changing a variable by a bit is so common that C++ has shortcuts:

coins += 5;   // same as coins = coins + 5
coins -= 2;   // same as coins = coins - 2
coins++;      // add 1
  • Add 5 to score with +=.

  • Then add 1 more with ++.

Comparing values

Comparisons ask a yes/no question: == equal (two = signs!), != not equal, <, >, <= and >=. The answer is a bool, which prints as 1 (true) or 0 (false). Put brackets around a comparison when you print it:

std::cout << (5 > 3) << "\n";   // 1
  • Print whether age is at least 18: (age >= 18).

  • On the next line, print whether age equals 30.

Put it together: pizza party

3 pizzas, 8 slices each, 10 hungry people. Let C++ work out how the slices split. Use the variables, not numbers you worked out yourself.

  • Create an int total that multiplies pizzas by slicesPerPizza.

  • Print Each person gets 2 slices using total / people.

  • Print Left over: 4 using %.

More in C++ Basics

Previous: Variables · Next: Conditionals