Skip to the workspace
Pebellslearn by building
Basic Operations  ›  Lesson

Arithmetic Operators

Arithmetic Operators 12 minArithmetic operators calculate from their operands. Integer division truncates toward zero, while remainder reports the remainder of integer division.

cpp / Arithmetic Operators

Explore each scene at your own pace.

01 · The rule

The rule

Arithmetic Operators

Arithmetic operators calculate from their operands. Integer division truncates toward zero, while remainder reports the remainder of integer division.

Compare integer and floating-point calculations at division and overflow boundaries.

Rocket Run gives the player an extra life for every 100 coins. With 250 coins, how many lives do they earn, and how many coins are left over? Two C++ operators answer that in one line each, as long as you know how integers divide.

The rule

Integer division drops the remainder; % hands you what was dropped.

The arithmetic operators are +, -, *, / and % (remainder). The key rule: the operand types decide the kind of arithmetic. If both sides of / are integers, the result is an integer and the fraction is simply cut off.

int coins = 250;
int extraLives = coins / 100;  // 2
int leftover   = coins % 100;  // 50

double exact = 250.0 / 100;    // 2.5, one side is a double

A few more tools you will use constantly:

  • Compound assignment: score += 10; means score = score + 10;. The same works for -=, *=, /= and %=.
  • Increment and decrement: ++level; adds one, --lives; subtracts one.
  • Precedence: *, / and % happen before + and -, just as in school maths. Use parentheses when in doubt.
  • Negative numbers: division rounds toward zero, so -7 / 2 is -3 and -7 % 2 is -1.

% only works on integers. For floating-point remainders there is std::fmod.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.