All lessons
LESSON 8/53Storing Information
Doing Maths
GOALAdd, subtract, multiply, divide, and find remainders.

C++ has + - * /. Two surprises: / between whole numbers gives a whole answer, and % gives the remainder.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int a = 7, b = 2;
cout << a + b << endl; // 9
cout << a - b << endl; // 5
cout << a * b << endl; // 14
cout << a / b << endl; // 3 <-- not 3.5!
cout << a % b << endl; // 1 remainder
cout << 7.0 / 2 << endl; // 3.5
return 0;
}> what you see
9 5 14 3 1 3.5
//LINE BY LINE
Watch it run
Lay seven counters out in rows, two to a row.
Integer division and %
Dividing two whole numbers throws the fraction away. 7 / 2 is 3, not 3.5.
cout << 7 / 2 << endl; // 3 ← бутархай хаягдав
cout << 7 % 2 << endl; // 1 ← үлдэгдэл
cout << 7 / 2.0 << endl; // 3.5 ← нэг нь бутархай бол зөв гарна> what you see
3 1 3.5
% (modulo) gives the remainder. It is used constantly — checking whether a number is even, for instance.
if (n % 2 == 0) cout << "тэгш / even";
else cout << "сондгой / odd";
int last = n % 10; // сүүлийн орон
int rest = n / 10; // сүүлийн орныг хассан ньWhich operation happens first
The same order as in maths: *, /, % first, then + and -. Brackets beat everything.
cout << 2 + 3 * 4 << endl; // 14 (3*4 эхэлнэ)
cout << (2 + 3) * 4 << endl; // 20 (хаалт эхэлнэ)> what you see
14 20
When in doubt, add brackets. Nobody was ever hurt by an extra pair; wrong answers hurt everybody.
Ready-made maths functions
Add #include <cmath> and you get a set of ready-made functions.
| Function | What it does |
|---|---|
sqrt(x) | квадрат язгуур / square root |
pow(x, y) | x-ийн y зэрэг / x to the power y |
abs(x) | үнэмлэхүй утга / absolute value |
round(x) | хамгийн ойрын бүхэл / nearest whole number |
min(a, b) · max(a, b) | бага/их нь / the smaller or larger |
#include <cmath>
cout << sqrt(16) << endl; // 4
cout << pow(2, 10) << endl; // 1024
cout << max(3, 9) << endl; // 9> what you see
4 1024 9