1.9 — Simple math

📘 Chapter 1⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Math operators#

C++ can do math, just like a calculator.

SymbolMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23 (!)
%remainder7 % 21

Expressions#

An expression is anything that makes a value. 2 + 3 is an expression. So is age * 12.

C++
int apples { 5 };int pears { 3 };int fruit { apples + pears };std::cout << "Fruit: " << fruit << '\n';
Output
Fruit: 8

The integer division surprise#

When you divide two whole numbers, C++ throws away the decimal part.

C++
std::cout << 7 / 2;    // prints 3, not 3.5std::cout << 7.0 / 2;  // prints 3.5
Watch out

int / int gives an int. If you want decimals, make at least one number a decimal, like 7.0.

Order of math#

C++ follows normal math order: * and / before + and -. Use brackets ( ) to choose the order yourself.

C++
std::cout << 2 + 3 * 4;    // 14std::cout << (2 + 3) * 4;  // 20

More about operators in 3.1 — Math operators.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.