Math

Math is very important in just about any kind of programming, and C++ is no exception.

Operation Operator
Addition +
Subtraction -
Multiplication *
Division /
Modulus (remainder) %
Increment (pre, post) ++var, var++
Decrement (pre, post) --var, var--

All your basic mathematical operations are here. Want to see them all1 in action?

#include <iostream>
 
int main()
{
    std::cout << "10 +  2 = " << 10 +  2 << std::endl;
    std::cout << "12 - 10 = " << 12 - 10 << std::endl;
    std::cout << " 2 *  5 = " <<  2 *  5 << std::endl;
    std::cout << "10 /  3 = " << 10 /  3 << std::endl;
}

You should see the following:

10 +  2 = 12
12 - 10 = 2
 2 *  5 = 10
10 /  3 = 3

Nice, huh?

Wait, what's that? 10 / 3 is NOT 3. It's 3.333.... Right? RIGHT?

Right! Why did it give 3 then? The answer is that we were using integers. Integers are basically numbers without anything after the decimal point. What happens if something should be after the decimal point, then? It truncates it!

Things like 1 / 10, even though the real answer is 0.1, would result in 0 with integer operations, because of the truncation. If When you need things with decimal values, you'll have to use floating point numbers, which we will cover later.

Congratulations, you can do math now! :) Coming up next, we have variables.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution 3.0 License