3.1 — Math operators
Read one box at a time. No rush.
The basics#
| Operator | Name | Example | Result |
|---|---|---|---|
+ | add | 5 + 2 | 7 |
- | subtract | 5 - 2 | 3 |
* | multiply | 5 * 2 | 10 |
/ | divide | 5 / 2 | 2 |
% | remainder | 5 % 2 | 1 |
-x | make 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 exactlyA very common use: checking if a number is even.
C++
int n { 8 };bool isEven { n % 2 == 0 }; // trueDividing 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); // 9Tip: press ← / → to move between lessons, / to search.