Arithmetic operators are used for performing basic mathematical operations on variables or values. C++ provides a set of standard arithmetic operators that you can use to perform addition, subtraction, multiplication, division, and more. Let's go through each arithmetic operator one by one:
1. Addition (+):
The addition operator (+) is used to add two operands together.
int a = 10;
int b = 20;
int result = a + b; // result will be 30
2. Subtraction (-):
The subtraction operator (-) is used to subtract the right-hand operand from the left-hand operand.
int a = 50;
int b = 30;
int result = a - b; // result will be 20
3. Multiplication (*):
The multiplication operator (*) is used to multiply two operands.
int a = 5;
int b = 6;
int result = a * b; // result will be 30
4. Division (/):
The division operator (/) is used to divide the left-hand operand by the right-hand operand.
int a = 50;
int b = 5;
int result = a / b; // result will be 10
5. Modulus (%):
The modulus operator (%) is used to find the remainder when the left-hand operand is divided by the right-hand operand.
int a = 20;
int b = 6;
int result = a % b; // result will be 2 (remainder of 20 / 6)
6. Increment (++) and Decrement (--):
The increment operator (++) is used to increase the value of a variable by one, and the decrement operator (--) is used to decrease the value of a variable by one.
int a = 5;
a++; // a will be 6
a--; // a will be 5 again
7. Compound Assignment Operators (+=, -=, *=, /=, %=):
C++ also provides compound assignment operators, which combine an arithmetic operation with assignment.
int a = 10;
a += 5; // equivalent to a = a + 5; (a will be 15)
a -= 3; // equivalent to a = a - 3; (a will be 12)
a *= 2; // equivalent to a = a * 2; (a will be 24)
a /= 4; // equivalent to a = a / 4; (a will be 6)
a %= 5; // equivalent to a = a % 5; (a will be 1)
Keep in mind that arithmetic operators have certain rules and precedence in C++. Parentheses can be used to control the order of evaluation.
Remember to use appropriate data types when using arithmetic operators to avoid potential overflow or precision issues, especially with floating-point numbers.
That's a summary of arithmetic operators in C++. They are essential for performing basic mathematical calculations in your C++ programs. Happy coding!
Top comments (0)