C++ Arithmetic Operators

Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands. For example, â€˜+â€™ is used for addition, â€˜â€˜ is used for subtraction,  â€˜*â€™ is used for multiplication, etc. In simple terms, arithmetic operators are used to perform arithmetic operations on variables and data; they follow the same relationship between an operator and an operand.

C++ Arithmetic operators are of 2 types:

1. Unary Arithmetic Operator
2. Binary Arithmetic Operator

1. Binary Arithmetic Operator

These operators operate or work with two operands. C++ provides 5 Binary Arithmetic Operators for performing arithmetic functions:

Example:

C++

 `// C++ program to execute all 5 ``// arithmetic function ``#include ``using` `namespace` `std; `` ` `int` `main() ``{ ``    ``int` `GFG1, GFG2; ``    ``GFG1 = 10; ``    ``GFG2 = 3; `` ` `    ``// printing the sum of GFG1 and GFG2 ``    ``cout<< ``"GFG1 + GFG2= "` `<< (GFG1 + GFG2) << endl; `` ` `    ``// printing the difference of GFG1 and GFG2 ``    ``cout << ``"GFG1 - GFG2 = "` `<< (GFG1 - GFG2) << endl; `` ` `    ``// printing the product of GFG1 and GFG2 ``    ``cout << ``"GFG1 * GFG2 = "` `<< (GFG1 * GFG2) << endl; `` ` `    ``// printing the division of GFG1 by GFG2 ``    ``cout << ``"GFG1 / GFG2 = "` `<< (GFG1 / GFG2) << endl; `` ` `    ``// printing the modulo of GFG1 by GFG2 ``    ``cout << ``"GFG1 % GFG2 = "` `<< (GFG1 % GFG2) << endl; `` ` `    ``return` `0; ``}`

Output
```GFG1 + GFG2= 13
GFG1 - GFG2 = 7
GFG1 * GFG2 = 30
GFG1 / GFG2 = 3
GFG1 % GFG2 = 1```

2. Unary Operator

These operators operate or work with a single operand.

Example:

C++

 `// C++ Program to demonstrate the  ``// increment and decrement operators ``#include ``using` `namespace` `std; `` ` `int` `main() ``{ ``    ``int` `x = 5; `` ` `    ``// This statement Incremented 1 ``    ``cout << ``"x++ is "` `<< x++ << endl; `` ` `    ``// This statement Incremented 1  ``    ``// from already Incremented ``    ``// statement resulting in  ``    ``// Incrementing of 2 ``    ``cout << ``"++x is "` `<< ++x << endl; `` ` `    ``int` `y = 10; ``   ` `    ``// This statement Decremented 1 ``    ``cout << ``"y-- is "` `<< y-- << endl; `` ` `    ``// This statement Decremented 1 ``    ``// from already Decremented ``    ``// statement resulting in  ``    ``// Decrementing of 2 ``    ``cout << ``"--y is "` `<< --y << endl; `` ` `    ``return` `0; ``}`

Output
```x++ is 5
++x is 7
y-- is 10
--y is 8```

In ++x, the variable’s value is first increased/incremented before being utilised in the program.

In x++, a variable’s value is assigned before it is increased/incremented.

Similarly happens for the decrement operator.

Previous
Next