Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Basic Operations  ›  Lesson

Arithmetic Operators

Arithmetic Operators 12 minC++ arithmetic uses the operand types to decide the result, so dividing two integers throws away the fraction while the remainder operator returns what was thrown away.

Arithmetic Operators

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.

The shortcut

Before you calculate, look at the types of the two operands. Both integers means integer arithmetic, whatever variable the answer is stored in.

Average score per roundStep 1 of 4
  1. The code

    int total = 17; int rounds = 4; double avg = total / rounds;

The trap is trusting the variable on the left. double avg does not reach back and change how the right side was calculated.

One more warning: an int has a maximum value (commonly about 2.1 billion). Adding past it with signed integers is undefined behaviour, so pick a wider type such as long long for big totals.

Drills

Answer fast — trust the rule.

quick drill

What is 17 / 5 in C++?

quick drill

What is 17 % 5?

quick drill

After double avg = 9 / 2;, what does avg hold?

quick drill

After int score = 10; score += 5 * 2;, what is score?

quick drill

What is -7 / 2 in modern C++?

Remember

  • Integer division drops the remainder; % hands you what was dropped.
  • Shortcut: check the operand types before you calculate.
  • Trap: storing the result in a double does not make the division exact.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe average that lost its decimals

Rocket Run shows the average score per round with double avg = total / rounds; where total is 17 and rounds is 4, both int. The screen shows 4 instead of 4.25. Explain why, and show a fix.