C++ Arithmetic Operators
Arithmetic operators in C++ are used to perform basic mathematical operations on numerical data types. These operators allow you to add, subtract, multiply, divide, and calculate the modulus (remainder) of numbers. Here’s a detailed explanation of each arithmetic operator in C++ along with examples:
1. Addition Operator (+
)
The addition operator is used to add two operands together.
Syntax:
result = operand1 + operand2;
Example:
#include <iostream> int main() { int a = 5, b = 10; int sum = a + b; // sum = 15 std::cout << "Sum: " << sum << std::endl; return 0; }
2. Subtraction Operator (-
)
The subtraction operator is used to subtract one operand from another.
Syntax:
result = operand1 - operand2;
Example:
#include <iostream> int main() { int a = 10, b = 4; int difference = a - b; // difference = 6 std::cout << "Difference: " << difference << std::endl; return 0; }
3. Multiplication Operator (*
)
The multiplication operator is used to multiply two operands.
Syntax:
result = operand1 * operand2;
Example:
#include <iostream> int main() { int a = 7, b = 3; int product = a * b; // product = 21 std::cout << "Product: " << product << std::endl; return 0; }
4. Division Operator (/
)
The division operator is used to divide one operand by another. When both operands are integers, the result is also an integer, and any remainder is discarded.
Syntax:
result = operand1 / operand2;
Example:
#include <iostream> int main() { int a = 20, b = 4; int quotient = a / b; // quotient = 5 std::cout << "Quotient: " << quotient << std::endl; return 0; }
Note: If you divide by zero, it will lead to a runtime error.
5. Modulus Operator (%
)
The modulus operator is used to find the remainder of the division of one operand by another. It is only applicable for integer data types.
Syntax:
result = operand1 % operand2;
Example:
#include <iostream> int main() { int a = 10, b = 3; int remainder = a % b; // remainder = 1 std::cout << "Remainder: " << remainder << std::endl; return 0; }
6. Operator Precedence and Associativity
- Precedence: Determines the order in which operators are evaluated in an expression. Arithmetic operators have different precedence levels.
- Associativity: Determines the order of evaluation when two operators of the same precedence level appear in an expression (left-to-right or right-to-left).
7. Example of Combined Arithmetic Operations
You can combine multiple arithmetic operations in a single expression. C++ will follow the operator precedence rules.
- Example:
#include <iostream> int main() { int a = 5, b = 10, c = 3; int result = a + b * c; // result = 5 + (10 * 3) = 35 std::cout << "Result: " << result << std::endl; // Outputs 35 return 0; }
8. Floating-Point Arithmetic
When using floating-point numbers, division can yield decimal results:
- Example:
#include <iostream> int main() { double a = 5.0, b = 2.0; double quotient = a / b; // quotient = 2.5 std::cout << "Quotient: " << quotient << std::endl; return 0; }