In this lesson, you will learn about C++ Operators, particularly Arithmetic Operators, and their usage, along with examples to better understand the topic.
An operator is a sign that instructs the compiler to carry out particular logical or mathematical operations on a value or variable. Operators are symbols that apply operations to values and variables. As an illustration, the operators +
and -
are used for addition and subtraction, respectively. There are four different types of operators in C++:
For performing arithmetic operations on variables, arithmetic operators are employed. As an illustration
var1 + var2;
In this case, the +
operator combines variables var1
and var2
. In a similar vein, C++ offers many other arithmetic operators.
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
– | Subtraction | a – b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulo Operation | a % b |
++ | Increment | a++ |
— | Decrement | a– |
The remainder is calculated using the modulo percentage operator. A = 13 divided by B = 4 leaves a residual of 1. Note that you can only use the numbers with the percentage operator.
As we may have expected, the operators +, –, and * compute addition, subtraction, and multiplication, respectively.
In our program, take note of the operation (a / b). When an integer is divided by another integer, the result is the quotient. However, we will receive the answer in decimals if the dividend or the divisor is a floating-point number like var3 / var2= 3.5 (7.0/2= 3.5)
#include <iostream> using namespace std; int main() { //declaring two variables int var1 = 7, var2 = 2; float var3 = 7.0; cout << "var1 = " << var1 << " var2 = " << var2 << endl; // Displaying the addition of var1 and var2 cout << "var1+ var2= " << (var1 + var2) << endl; // Displaying the difference of var1 and var2 cout << "var1- var2= " << (var1 - var2) << endl; // Displaying the product of var1 and var2 cout << "var1* var2= " << (var1 * var2) << endl; // Displaying the division of var1 by var2 cout << "var1/ var2= " << (var1 / var2) << endl; // Displaying the division of var3 by var2 cout << "var3/ var2= " << (var3 / var2) << endl; // Displaying the modulo of var1 by var2 cout << "var1% var2= " << (var1 % var2) << endl; return 0; }
Output
var1 = 7 var2 = 2 var1+ var2= 9 var1- var2= 5 var1* var2= 14 var1/ var2= 3 var3/ var2= 3.5 var1% var2= 1
Additionally, the increment and decrement operators in C++ are ++
and --
, respectively.
++ increases the operand’s value by 1; — decreases it by 1.
Example
#include <iostream> using namespace std; int main() { int var1 = 7, var2 = 2; cout << "var1 = " << (++var1) << " var2 = " << (--var2) << endl; return 0; }
Output
var1 = 8 var2 = 1
This concludes the C++ Arithmetic Operators lesson. In the next lesson, you will learn about Assignment Operators in C++.