All lessons

Numbers & Math

7 min · C++

Do math with int variables and the basic operators.

C++ · Numbers & Math0/5 cleared

Enemy 1 of 5

The basic operators

This code multiplies price by quantity and prints the result. Watch out: dividing two ints drops the decimal part, so 7 / 2 gives 3. Press Run to see it.

Why this works

C++'s int type stores whole numbers (no decimal point). The four basic arithmetic operators work exactly like you'd expect from math class: + for addition, - for subtraction, * for multiplication, and / for division.

One gotcha that trips up almost everyone at first: dividing two ints in C++ gives you integer division, meaning the decimal part is thrown away. 7 / 2 evaluates to 3, not 3.5. If you want a precise decimal answer, at least one of the values needs to be a floating-point type like double.

You can combine variables and literal numbers freely in the same expression, and C++ follows the usual order of operations (multiplication and division before addition and subtraction), just like in algebra.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.