A girl and a robot thinking together

Think together · Start with a story

A girl has 3 bags of candy with 4 pieces in each, then gets 2 more. Which part will the robot calculate first?

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Candy in the bags3 times 4 is 12
  2. Add the loose candy12 plus 2
  3. Final result14

Operators express actions such as addition, subtraction, multiplication, and division. Multiplication and division usually come before addition and subtraction; parentheses make the intended order clear.

So 3 * 4 + 2 gives 14. The multiplication is done before the addition.

01Four basic arithmetic operators

+

Addition

-

Subtraction

*

Multiplication

/

Division

int a = 8;
int b = 3;

a + b;  // 11
a - b;  // 5
a * b;  // 24

02What is special about integer division?

If both operands are integers, C++ performs integer division:

8 / 3   // result is 2

The fractional part is truncated toward zero.

-8 / 3  // result is -2

03How do you get a decimal result?

Make at least one operand a floating-point number:

8.0 / 3.0
8.0 / 3
static_cast<double>(8) / 3

Each expression uses floating-point division and gives a result close to 2.666....

04Multiplication and division before addition and subtraction?

C++ has operator precedence:

2 + 3 * 4   // 14

Multiplication comes before addition.

To add first:

(2 + 3) * 4   // 20

05Can a calculation result overflow?

Yes. For example, multiplying two very large int values may produce a result outside the range that int can represent.

Overflow of a signed integer is undefined behavior.

06What happens if you divide by 0?

Dividing an integer by 0 is an invalid operation and causes undefined behavior.

int x = 10 / 0; // Error

That is why a program often needs to check that the divisor is not 0 before dividing.

What you have learned

  • + - * / perform basic arithmetic.
  • Integer division truncates the fractional part toward zero.
  • Floating-point division needs a floating-point type to take part.
  • Expressions follow operator precedence; parentheses can make the order clear.
  • Integer calculations can overflow, and a divisor must not be 0.

Next: %: Why Is the Remainder So Useful?

Your turn to try

Is 2 + 3 * 4 equal to 20? How would you change it to add first, then multiply?

Ready? Open to see the explanation

The original expression multiplies first, so the result is 14. Write (2 + 3) * 4 to get 20; the parentheses change how the expression is grouped.