โ C++ Arithmetic Operators โ Perform Basic Mathematical Operations
๐งฒ Introduction โ What Are Arithmetic Operators in C++?
Arithmetic operators in C++ are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. These operators work with numeric data types and are essential in calculations, loops, algorithms, and data processing.
๐ฏ In this guide, youโll learn:
- List of arithmetic operators
- Syntax and usage examples
- Operator precedence rules
- Common pitfalls and best practices
โ List of C++ Arithmetic Operators
| Operator | Symbol | Description | Example | Result |
|---|---|---|---|---|
| Addition | + | Adds two values | a + b | 15 |
| Subtraction | - | Subtracts second value from first | a - b | 5 |
| Multiplication | * | Multiplies two values | a * b | 50 |
| Division | / | Divides numerator by denominator | a / b | 2 (int) |
| Modulus | % | Returns remainder | a % b | 0 |
๐ Where
int a = 10; int b = 5;
โ๏ธ Example โ Basic Arithmetic
#include <iostream>
using namespace std;
int main() {
int a = 15, b = 4;
cout << "Addition: " << a + b << endl;
cout << "Subtraction: " << a - b << endl;
cout << "Multiplication: " << a * b << endl;
cout << "Division: " << a / b << endl;
cout << "Modulus: " << a % b << endl;
return 0;
}
Output:
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3
Modulus: 3
๐บ Operator Precedence (High to Low)
*,/,%+,-
int result = 10 + 5 * 2; // 10 + (5 * 2) = 20
โ ๏ธ Common Mistakes
| โ Mistake | โ Fix |
|---|---|
| Division by zero | Ensure denominator is not zero |
| Integer division with float result | Use typecasting: (float)a / b |
Using % with floats | Only works with integers in standard C++ |
๐ Increment and Decrement (Unary Arithmetic)
These are closely related to arithmetic operators:
int x = 5;
x++; // Post-increment
++x; // Pre-increment
๐ Summary โ Recap & Next Steps
๐ Key Takeaways:
- Arithmetic operators perform essential mathematical operations
%returns remainder and works with integers only- Operator precedence impacts the result of expressions
- Use typecasting for accurate floating-point division
โ๏ธ Real-World Relevance:
From calculations in financial systems to physics engines in games, arithmetic operators are core tools in C++ programming.
โ FAQs โ C++ Arithmetic Operators
โ Can I use % with float or double in C++?
โ No. Use fmod() from <cmath> instead.
โ What happens in integer division?
โ
Decimal parts are truncated. 5 / 2 gives 2.
โ How to ensure precise division?
โ
Typecast operands:
float result = (float)a / b;
โ What is the precedence of * and +?
โ
* has higher precedence than +, so it’s evaluated first.
Share Now :
