How to Use Arithmetic Operators in C++: Syntax and Examples
In C++, you use
+, -, *, /, and % as arithmetic operators to perform addition, subtraction, multiplication, division, and modulus operations on numbers. These operators work with variables and literals to calculate values in expressions.Syntax
Arithmetic operators in C++ are used between two operands (numbers or variables) to perform calculations. The common operators are:
+for addition-for subtraction*for multiplication/for division%for modulus (remainder of division, only for integers)
Example syntax: result = a + b; adds a and b and stores the result.
cpp
int a = 5; int b = 3; int sum = a + b; // sum is 8 int diff = a - b; // diff is 2 int prod = a * b; // prod is 15 int quot = a / b; // quot is 1 (integer division) int rem = a % b; // rem is 2 (remainder)
Example
This example shows how to use arithmetic operators to calculate and print results of basic math operations.
cpp
#include <iostream> int main() { int x = 10; int y = 4; std::cout << "x + y = " << x + y << "\n"; std::cout << "x - y = " << x - y << "\n"; std::cout << "x * y = " << x * y << "\n"; std::cout << "x / y = " << x / y << "\n"; std::cout << "x % y = " << x % y << "\n"; return 0; }
Output
x + y = 14
x - y = 6
x * y = 40
x / y = 2
x % y = 2
Common Pitfalls
Common mistakes when using arithmetic operators in C++ include:
- Using
/with integers results in integer division, which discards the decimal part. - Using
%with non-integer types causes errors because modulus works only with integers. - Dividing by zero causes a runtime error or crash.
Always ensure the divisor is not zero and use floating-point types for decimal division.
cpp
/* Wrong: integer division loses decimals */ int a = 7; int b = 2; int result = a / b; // result is 3, not 3.5 /* Right: use float or double for decimal division */ double c = 7.0; double d = 2.0; double result2 = c / d; // result2 is 3.5
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division (integer or floating) | 5 / 2 | 2 (int), 2.5 (float) |
| % | Modulus (remainder) | 5 % 3 | 2 |
Key Takeaways
Use +, -, *, /, and % to perform basic math operations in C++.
Integer division truncates decimals; use float or double for precise division.
Modulus operator % works only with integers to find the remainder.
Avoid dividing by zero to prevent runtime errors.
Arithmetic operators work between variables and literals in expressions.