C++ Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
a + b;
Here, the +
operator is used to add two variables a and b. Similarly there are various other arithmetic operators in C++.
Operator | Operation |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo Operation (Remainder after division) |
Example 1: Arithmetic Operators
#include <iostream> using namespace std; int main() { int a, b; a = 7; b = 2; // printing the sum of a and b cout << "a + b = " << (a + b) << endl; // printing the difference of a and b cout << "a - b = " << (a - b) << endl; // printing the product of a and b cout << "a * b = " << (a * b) << endl; // printing the division of a by b cout << "a / b = " << (a / b) << endl; // printing the modulo of a by b cout << "a % b = " << (a % b) << endl; return 0; }
Output
a + b = 9 a - b = 5 a * b = 14 a / b = 3 a % b = 1
Here, the operators +
, -
and *
compute addition, subtraction, and multiplication respectively as we might have expected.
/ Division Operator
Note the operation (a / b)
in our program. The /
operator is the division operator.
As we can see from the above example, if an integer is divided by another integer, we will get the quotient. However, if either divisor or dividend is a floating-point number, we will get the result in decimals.
In C++, 7/2 is 3 7.0 / 2 is 3.5 7 / 2.0 is 3.5 7.0 / 2.0 is 3.5
% Modulo Operator
The modulo operator %
computes the remainder. When a = 9
is divided by b = 4
, the remainder is 1.
Note: The %
operator can only be used with integers.
Increment and Decrement Operators
C++ also provides increment and decrement operators: ++
and --
respectively.
++
increases the value of the operand by 1--
decreases it by 1
For example,
int num = 5; // increment operator ++num; // 6
Here, the code ++num;
increases the value of num by 1.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators #include <iostream> using namespace std; int main() { int a = 10, b = 100, result_a, result_b; // incrementing a by 1 and storing the result in result_a result_a = ++a; cout << "result_a = " << result_a << endl; // decrementing b by 1 and storing the result in result_b result_b = --b; cout << "result_b = " << result_b << endl; return 0; }
Output
result_a = 11 result_b = 99
In the above program, we have used the ++
and --
operators as prefixes (++a and –b). However, we can also use these operators as postfix (a++ and b–).