3.1 — Math operators

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

The basics#

OperatorNameExampleResult
+add5 + 27
-subtract5 - 23
*multiply5 * 210
/divide5 / 22
%remainder5 % 21
-xmake negative-5-5

Remainder (%)#

% gives what is left over after dividing. It is called modulo or remainder.

C++
std::cout << 10 % 3;   // 1, because 10 = 3 + 3 + 3, with 1 left overstd::cout << 12 % 4;   // 0, because 4 fits exactly

A very common use: checking if a number is even.

C++
int n { 8 };bool isEven { n % 2 == 0 };   // true

Dividing by zero#

C++ — wrong ✗
int x { 10 / 0 };   // crash or undefined behavior!
Watch out

Never divide by zero. If a number comes from the user, check it first.

Powers and square roots#

C++ has no "power" operator. Use the <cmath> tools:

C++
#include <cmath> std::cout << std::pow(2, 10);   // 1024std::cout << std::sqrt(81);     // 9
Finished reading? Tick it off. Your progress is saved in this browser.

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