Simple C++ Math
Learn about the arithmetic operators used in C++.
Up till now, we have only created variables, assigned them values, and displayed their values on the screen. It’s now time to use them to solve actual problems—mathematical ones. For that, we first need to see how C++ enables arithmetic operations.
Arithmetic operations in C++
The arithmetic operators in C++ are listed below.
Symbols | Arithmetic Operations |
| Add |
| Subtract |
| Divide |
| Multiply |
| Remainder (or modulus division) |
Let’s examine how to use these operations while coding in C++. We start with a simple example that doesn’t use variables and only outputs the result of the mathematical operations.
#include <iostream>using namespace std;int main() {cout << 15 + 5 << endl; //Addcout << 15 - 5 << endl; //Subtractcout << 15 * 5 << endl; //Multiplycout << 15 / 5 << endl; //Dividecout << 15 % 5 << endl; //Remainderreturn 0;}
In the above code, we see how the arithmetic operation can be performed on integer values in C++. We print the results of the operations performed on the same values.
These are all binary operators—so called because they each take two operands, one on the left of the operator and other on the right of it. There are also unary operators that only take one operand. We will discuss these later in the lesson when we talk about increment and decrement operators.
Now let’s do the same thing but using variables.
#include <iostream>using namespace std;int main() {int num1, num2, res;num1 = 15;num2 = 5;res = 0;res = num1 + num2; //Addcout << res << endl;res = num1 - num2; //Subtractcout << res << endl;res = num1 * num2; //Multiplycout << res << endl;res = num1 / num2; //Dividecout << res << endl;res = num1 % num2; //Remaindercout << res << endl;return 0;}
Notice how we are reusing the res
variable for each operation. We could have declared five different variables for each operation. But since we did not need the values once they were displayed, we decided to use a single variable for storing the result, and overwriting the value once it was displayed. This is more efficient and uses less memory. Note that we could even completely do away with the res
variable and directly cout
the arithmetic operations’ results, for example cout << num1 + num2 << endl;
.
Dividing integers
In the above example, 15 % 5
gave us 0
—which is the remainder, and 15 / 5
gave us 3
—which is the quotient.
Remember: The remainder operator only takes integer operands. It doesn't work for float, double, or any other data type.
Let’s change the denominator. Suppose we were to divide 15
by 4
. 15 % 4
would give us the remainder 3
—displayed on the screen. But what about 15 / 4
?
Will we get 3.75
?
No! We will get 3
. Always remember that dividing two integers gives an integer result. The fractional part in the result is discarded—no rounding occurs.
If you want the result to retain the fractional part, use float
or double
data type instead of int
. We will cover this point in greater detail in the next lesson. For now, just look at the following playground that gives us the fractional part as well.
#include <iostream>using namespace std;int main() {cout << 15 / 4 << endl;cout << 15.0 / 4.0 << endl;cout << 15.0 / 4 << endl;cout << 15 / 4.0 << endl;return 0;}
In the above code, we have used multiple variations for dividing the two numbers. In the first variation, two integers 15
and 4
are divided, and so the fractional part is discarded. In the second, third, and fourth variations, either one of the two or both numbers has a .0
added to them. Why does this work? When the compiler encounters a decimal point, it treats the number as a float
instead of an int
. When we divide two floats or one integer and one float, the resulting value would be of float type. The same holds if we use double instead of float.
Numerical inaccuracies
Some mistakes may be made while performing arithmetic operations in C++. Let’s review them here so we can avoid them during our coding practices.
Cancellation error: When two numbers with a huge difference in magnitude are used as operands to arithmetic operations, the effect of the smaller operand may be truncated because it doesn’t really affect the result. The compiler usually rounds off the result for the user.
Arithmetic underflow: If the operands to the multiplication operation are so small that they are close to zero, the compiler may print the result as a simple
0
.Arithmetic overflow: If the operands to the addition and multiplication operations are too large, the result may be too large to fit in, causing overflow. It throws an error. You can uncomment Line 8 in the playground below to see that it throws an error.
Here, take a look at how the compiler comprehends and prints the results of these operations.
#include <iostream>using namespace std;int main() {//Cancellation Errorcout << 1100.0 + 0.00000000000008 << endl;//Aritmetic overflow//cout << 9999999999999999999999 + 8989898989898989898 << endl;return 0;}
Operator precedence
The C++ compiler processes the arithmetic operations in a statement in a precise, determined order by following the rules of operator precedence, similar to what we’ve been doing in basic algebra.
Parentheses: It is a practice that the operations within the parentheses are computed first. Parentheses are considered the highest level of precedence. In the case where there are multiple parentheses in nested form, the innermost parentheses are computed first.
Multiplication, division, and remainder: The second precedence after parentheses is applied to the multiplication, division, and remainder operations in left-to-right order. All three of these operations have the same precedence.
Addition and subtraction: The addition and subtraction operations are performed last; both have the same precedence. If there are multiple addition and subtraction operations in a statement, precedence is applied from left to right.
When we are discussing the precedence of operations from left to right, we refer to the associativity of the operators. For example, look at the example below:
x + y - z
This means that x
, y
are added first and then z
is subtracted from it. It is important to know that there are operators that associate from right to left; we’ll discuss them later in the course.
What is the result of the following operation?
12 / 3 * 2
Example
If you try to compute the given expression:
20 + 30 * 2 / 10 - 3
According to the C++ operator precedence, it will first compute 30 * 2 = 60
. Then divide 60 / 10 = 6
. Both multiplication and division have the same precedence, but evaluation is done from left to right. After that, add 20 + 6 = 26
and subtract 26 - 3 = 23
. Again, addition has the same precedence as subtraction, but evaluation is done from left to right. So, the final answer is 23
.
Give it a try!
#include <iostream>using namespace std;int main() {// 20 + 30 * 2 / 10 - 3cout << "Answer is " << 20 + 30 * 2 / 10 - 3 << endl;return 0;}
Quiz
Attempt the following quiz to assess your understanding of simple C++ Maths.
What is the output of the following expression?
2 + 15 * ( 7 + (2 * 0) )
107
119
0
Reducing keystrokes
We know that arithmetic operators are binary operators. Therefore, they require 2 operands to operate on. Usually, to add two numbers and save them in the first operand, we use the following statement:
a = a + b;
But what if we can do the same, but using a different operator like +=
. Let’s see how we can do this:
a += b;
What it does is that it adds the value of b
to a
and saves it in the variable a
. This approach works for other arithmetic operations as well. These are called compound assignment operators.
Symbols | Operations |
| Addition assignment |
| Subtraction assignment |
| Multiplication assignment |
| Division assignment |
| Remainder assignment |
Here you can also test the working of the compound assignment operators in the playground given:
#include <iostream>using namespace std;int main() {int a, b;a = 9;b = 3;cout << "a:" << a <<endl; // a = 9cout << "b:" << b << endl; // b = 3a += b;cout << "a += b" << endl;cout << "a:" << a <<endl; // a = 12cout << "b:" << b << endl; // b = 3a -= b;cout << "a -= b" << endl;cout << "a:" << a <<endl; // a = 9cout << "b:" << b << endl; // b = 3a *= b;cout << "a *= b" << endl;cout << "a:" << a <<endl; // a = 27cout << "b:" << b << endl; // b = 3a /= b;cout << "a /= b" << endl;cout << "a:" << a <<endl; // a = 9cout << "b:" << b << endl; // b = 3a %= b;cout << "a %= b" << endl;cout << "a:" << a <<endl; // a = 0cout << "b:" << b << endl; // b = 3return 0;}
You can see that it performs the exact same operation as the normal arithmetic operation. But to save memory, we don’t have to make an extra variable res
to store the result. There is, however, one problem with this implementation: the first operand won’t retain its value, so if you have to retain its value, it is recommended to use another operator to save its result.
The increment and decrement operators
A very common operation in programming, especially when working with loops, is increasing the variable’s value by 1
, ( val = val + 1
) or decreasing it by 1
, ( val = val - 1
). C++ provides a shorthand way of doing this using the increment (++
) and decrement (-–
) operators.
The post-increment and post-decrement operation
Have a look at the following code. When the increment and decrement operators are written to the right of the variable that they are modifying ( val++
or val-–
), it is called post increment or decrement. What this means is that the value of the variable would be used first in the expression and modified later.
#include <iostream>using namespace std;int main() {int val = 0;//Post-incrementcout << val << endl;cout << val++ << endl;cout << val++ << endl;//Post-decrementcout << val << endl;cout << val-- << endl;cout << val-- << endl;//Final valuecout << val << endl;return 0;}
When you execute the above code, what do you expect to be shown on the screen? Remember, when the operator is written to the right of the variable, the value stored inside the variable is used first and modified later.
When line 8 is executed, the value stored in the variable
val
is displayed. This value is0
.When line 9 is executed, the value stored in the variable
val
is displayed, which is0
—and after that, the value is incremented to1
.When line 10 is executed, the value stored in the variable
val
is displayed, which is1
from the previous line's execution, and after that, the value is incremented to2
.When line 13 is executed, the value stored in the variable
val
is displayed. This value is2
.When line 14 is executed, the value stored in the variable
val
is displayed, which is2
—and after that, the value is decremented to1
.When line 15 is executed, the value stored in the variable
val
is displayed, which is1
—and after that, the value is decremented to0
.When line 18 is executed, the value stored in the variable
val
is displayed. This value is0
.
The pre-increment and pre-decrement operations
What happens when the increment or decrement operator is written to the left of the variable ( ++val
or --val
)?
It becomes a pre-increment or pre-decrement operator. This means that the value inside the variable is modified first and used in the expression after that. Have a look at the following code. Try to work out the output yourself before executing the code to see if you were right.
#include <iostream>using namespace std;int main() {int val = 0;//Pre-decrementcout << val << endl;cout << --val << endl;cout << val << endl;//Pre-incrementcout << val << endl;cout << ++val << endl;cout << val << endl;return 0;}
Notice how, unlike the previous playground, here the value being printed is already modified before it is displayed.
Test your understanding with the quiz below.
What is the output of the following code?
int x = 5;
cout << x++ << " ";
cout << ++x << endl;