Simple C++ Maths
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 take a look at 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-given code, we see how the arithmetic operation can be performed on the integer values in C++. We print the values of the result of the operations performaed 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.
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 operation's 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 doesnt 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 ...