Doing Maths

The maths operators

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

The integer division surprise

When you divide two ints, C++ gives you an int back. The decimal part is thrown away:

#include <iostream>
using namespace std;

int main() {
    cout << 7 / 2 << "\n";       // both are ints: 3
    cout << 7.0 / 2 << "\n";     // one is a double: 3.5
    cout << 10 / 3 << "\n";
    cout << 10.0 / 3 << "\n";
    return 0;
}

Output

3
3.5
3
3.33333

Remember: If at least one number has a decimal point, you get a decimal answer. If both are whole numbers, you get a whole number.

The remainder operator %

% (called modulo) gives what is left over after dividing whole numbers. It is more useful than it looks:

#include <iostream>
using namespace std;

int main() {
    cout << 17 % 5 << "\n";     // 17 = 3*5 + 2, so 2 is left over
    cout << 10 % 2 << "\n";     // 0 left over: 10 is even
    cout << 7 % 2 << "\n";      // 1 left over: 7 is odd

    int totalMinutes = 135;
    cout << totalMinutes / 60 << " hours and " << totalMinutes % 60 << " minutes\n";
    return 0;
}

Output

2
0
1
2 hours and 15 minutes

Think of it like this: You share 17 sweets between 5 friends. Each gets 17 / 5 = 3 sweets, and 17 % 5 = 2 sweets are left over for you.

Order of operations

C++ follows normal maths rules: *, / and % happen before + and -. Use brackets to choose the order yourself:

#include <iostream>
using namespace std;

int main() {
    cout << 2 + 3 * 4 << "\n";      // 3*4 first: 14
    cout << (2 + 3) * 4 << "\n";    // brackets first: 20
    return 0;
}

Output

14
20

Common mistake: Dividing by zero. 5 / 0 with ints makes the program crash. Check a number isn't 0 before you divide by it.

HOME LABS COMMUNITY DASHBOARD