Coming Soon
This lesson is currently being developed
Arithmetic operators
Master basic mathematical operations in C++.
What to Expect
Comprehensive explanations with practical examples
Interactive coding exercises to practice concepts
Knowledge quiz to test your understanding
Step-by-step guidance for beginners
Development Status
Content is being carefully crafted to provide the best learning experience
Preview
Early Preview Content
This content is still being developed and may change before publication.
6.2 — Arithmetic operators
In this lesson, you'll learn about C++ arithmetic operators, understand how they work with different data types, and discover common pitfalls and best practices for mathematical operations in your programs.
What are arithmetic operators?
Arithmetic operators perform mathematical calculations on numeric values. They're the basic building blocks for any computational work in C++, from simple calculations to complex mathematical algorithms.
C++ provides five basic arithmetic operators:
+
(addition)-
(subtraction)*
(multiplication)/
(division)%
(remainder/modulo)
These operators work with both integer and floating-point types, though they behave slightly differently depending on the data types involved.
Addition operator (+)
The addition operator adds two values together:
Basic addition
#include <iostream>
int main()
{
// Integer addition
int a = 5;
int b = 3;
int sum = a + b;
// Floating-point addition
double x = 3.14;
double y = 2.71;
double floatSum = x + y;
// Mixed type addition (integer promoted to double)
double mixed = a + x;
std::cout << "Integer addition: " << a << " + " << b << " = " << sum << std::endl;
std::cout << "Float addition: " << x << " + " << y << " = " << floatSum << std::endl;
std::cout << "Mixed addition: " << a << " + " << x << " = " << mixed << std::endl;
return 0;
}
Output:
Integer addition: 5 + 3 = 8
Float addition: 3.14 + 2.71 = 5.85
Mixed addition: 5 + 3.14 = 8.14
Addition with different types
#include <iostream>
int main()
{
// Character addition (ASCII values)
char letter = 'A'; // ASCII 65
char result = letter + 1;
// Boolean addition (true = 1, false = 0)
bool flag1 = true;
bool flag2 = false;
int boolSum = flag1 + flag2 + flag1; // 1 + 0 + 1
// Size type addition
size_t size1 = 100;
size_t size2 = 50;
size_t totalSize = size1 + size2;
std::cout << "Character + 1: " << letter << " + 1 = " << result << std::endl;
std::cout << "Boolean sum: " << flag1 << " + " << flag2 << " + " << flag1 << " = " << boolSum << std::endl;
std::cout << "Size addition: " << size1 << " + " << size2 << " = " << totalSize << std::endl;
return 0;
}
Output:
Character + 1: A + 1 = B
Boolean sum: 1 + 0 + 1 = 2
Size addition: 100 + 50 = 150
Subtraction operator (-)
The subtraction operator subtracts the second value from the first:
Basic subtraction
#include <iostream>
int main()
{
// Integer subtraction
int a = 10;
int b = 6;
int difference = a - b;
// Floating-point subtraction
double x = 7.5;
double y = 2.3;
double floatDifference = x - y;
// Subtraction resulting in negative
int negative = 3 - 8;
std::cout << "Integer subtraction: " << a << " - " << b << " = " << difference << std::endl;
std::cout << "Float subtraction: " << x << " - " << y << " = " << floatDifference << std::endl;
std::cout << "Negative result: 3 - 8 = " << negative << std::endl;
return 0;
}
Output:
Integer subtraction: 10 - 6 = 4
Float subtraction: 7.5 - 2.3 = 5.2
Negative result: 3 - 8 = -5
Unary minus (negation)
The minus operator can also be used as a unary operator to negate values:
#include <iostream>
int main()
{
int positive = 42;
int negative = -positive; // Unary minus
int backToPositive = -negative; // Double negation
double pi = 3.14159;
double negativePi = -pi;
std::cout << "Original: " << positive << std::endl;
std::cout << "Negated: " << negative << std::endl;
std::cout << "Double negated: " << backToPositive << std::endl;
std::cout << "Negative pi: " << negativePi << std::endl;
return 0;
}
Output:
Original: 42
Negated: -42
Double negated: 42
Negative pi: -3.14159
Multiplication operator (*)
The multiplication operator multiplies two values:
Basic multiplication
#include <iostream>
int main()
{
// Integer multiplication
int length = 12;
int width = 8;
int area = length * width;
// Floating-point multiplication
double radius = 5.0;
double pi = 3.14159;
double circumference = 2 * pi * radius;
// Large numbers
long long big1 = 1000000;
long long big2 = 2000000;
long long bigProduct = big1 * big2;
std::cout << "Rectangle area: " << length << " * " << width << " = " << area << std::endl;
std::cout << "Circumference: 2 * " << pi << " * " << radius << " = " << circumference << std::endl;
std::cout << "Large multiplication: " << big1 << " * " << big2 << " = " << bigProduct << std::endl;
return 0;
}
Output:
Rectangle area: 12 * 8 = 96
Circumference: 2 * 3.14159 * 5 = 31.4159
Large multiplication: 1000000 * 2000000 = 2000000000000
Multiplication with different types
#include <iostream>
int main()
{
// Mixed integer and floating-point
int count = 5;
double price = 12.99;
double total = count * price;
// Character multiplication (ASCII values)
char digit = '3'; // ASCII 51
int multiplied = digit * 2;
// Boolean multiplication
bool isActive = true;
int factor = 10;
int result = isActive * factor; // true * 10 = 1 * 10 = 10
std::cout << "Shopping total: " << count << " * $" << price << " = $" << total << std::endl;
std::cout << "Character * 2: '" << digit << "' * 2 = " << multiplied << " (ASCII " << static_cast<int>(digit) << " * 2)" << std::endl;
std::cout << "Boolean multiplication: " << isActive << " * " << factor << " = " << result << std::endl;
return 0;
}
Output:
Shopping total: 5 * $12.99 = $64.95
Character * 2: '3' * 2 = 102 (ASCII 51 * 2)
Boolean multiplication: 1 * 10 = 10
Division operator (/)
The division operator divides the first value by the second. Its behavior depends significantly on the data types involved:
Integer division vs. floating-point division
#include <iostream>
int main()
{
// Integer division - truncates result
int intA = 10;
int intB = 3;
int intResult = intA / intB; // 10/3 = 3.333... truncated to 3
// Floating-point division - preserves decimal
double doubleA = 10.0;
double doubleB = 3.0;
double doubleResult = doubleA / doubleB;
// Mixed division - integer promoted to double
double mixedResult = intA / doubleB;
std::cout << "Integer division: " << intA << " / " << intB << " = " << intResult << std::endl;
std::cout << "Float division: " << doubleA << " / " << doubleB << " = " << doubleResult << std::endl;
std::cout << "Mixed division: " << intA << " / " << doubleB << " = " << mixedResult << std::endl;
return 0;
}
Output:
Integer division: 10 / 3 = 3
Float division: 10 / 3 = 3.33333
Mixed division: 10 / 3 = 3.33333
Important integer division behavior
#include <iostream>
int main()
{
// Integer division always truncates toward zero
std::cout << "Positive integer division:" << std::endl;
std::cout << "7 / 3 = " << (7 / 3) << std::endl; // 2
std::cout << "8 / 3 = " << (8 / 3) << std::endl; // 2
std::cout << "9 / 3 = " << (9 / 3) << std::endl; // 3
std::cout << "\nNegative integer division:" << std::endl;
std::cout << "-7 / 3 = " << (-7 / 3) << std::endl; // -2
std::cout << "7 / -3 = " << (7 / -3) << std::endl; // -2
std::cout << "-7 / -3 = " << (-7 / -3) << std::endl; // 2
// To get floating-point division, use floating-point types
std::cout << "\nFloating-point equivalents:" << std::endl;
std::cout << "7.0 / 3.0 = " << (7.0 / 3.0) << std::endl;
std::cout << "-7.0 / 3.0 = " << (-7.0 / 3.0) << std::endl;
return 0;
}
Output:
Positive integer division:
7 / 3 = 2
8 / 3 = 2
9 / 3 = 3
Negative integer division:
-7 / 3 = -2
7 / -3 = -2
-7 / -3 = 2
Floating-point equivalents:
7.0 / 3.0 = 2.33333
-7.0 / 3.0 = -2.33333
Getting fractional results from integers
#include <iostream>
int main()
{
int numerator = 22;
int denominator = 7;
// ❌ Wrong: both integers result in integer division
double wrongResult = numerator / denominator;
// ✅ Right: convert at least one operand to floating-point
double rightResult1 = static_cast<double>(numerator) / denominator;
double rightResult2 = numerator / static_cast<double>(denominator);
double rightResult3 = static_cast<double>(numerator) / static_cast<double>(denominator);
// Alternative: use floating-point literals
double rightResult4 = 22.0 / 7.0;
std::cout << "Integer division result: " << wrongResult << std::endl;
std::cout << "Cast numerator: " << rightResult1 << std::endl;
std::cout << "Cast denominator: " << rightResult2 << std::endl;
std::cout << "Cast both: " << rightResult3 << std::endl;
std::cout << "Float literals: " << rightResult4 << std::endl;
return 0;
}
Output:
Integer division result: 3
Cast numerator: 3.14286
Cast denominator: 3.14286
Cast both: 3.14286
Float literals: 3.14286
Division by zero
Division by zero is undefined behavior and should be avoided:
Handling division by zero
#include <iostream>
int main()
{
int dividend = 10;
int divisor = 0;
// Check for division by zero before dividing
if (divisor != 0) {
int result = dividend / divisor;
std::cout << "Result: " << result << std::endl;
} else {
std::cout << "Error: Division by zero!" << std::endl;
}
// Safe division function
auto safeDivide = [](double a, double b) -> double {
if (b != 0.0) {
return a / b;
} else {
std::cout << "Warning: Division by zero, returning 0" << std::endl;
return 0.0;
}
};
std::cout << "Safe division: " << safeDivide(10.0, 2.0) << std::endl;
std::cout << "Safe division by zero: " << safeDivide(10.0, 0.0) << std::endl;
return 0;
}
Output:
Error: Division by zero!
Safe division: 5
Warning: Division by zero, returning 0
Safe division by zero: 0
Combining arithmetic operators
Arithmetic operators can be combined in complex expressions:
Order of operations (precedence)
#include <iostream>
int main()
{
// Remember: multiplication and division before addition and subtraction
int result1 = 2 + 3 * 4; // = 2 + 12 = 14
int result2 = (2 + 3) * 4; // = 5 * 4 = 20
int result3 = 10 - 6 / 2; // = 10 - 3 = 7
int result4 = (10 - 6) / 2; // = 4 / 2 = 2
// Multiple operations
int result5 = 2 * 3 + 4 * 5; // = 6 + 20 = 26
int result6 = 100 / 5 / 2; // = 20 / 2 = 10 (left-to-right)
std::cout << "2 + 3 * 4 = " << result1 << std::endl;
std::cout << "(2 + 3) * 4 = " << result2 << std::endl;
std::cout << "10 - 6 / 2 = " << result3 << std::endl;
std::cout << "(10 - 6) / 2 = " << result4 << std::endl;
std::cout << "2 * 3 + 4 * 5 = " << result5 << std::endl;
std::cout << "100 / 5 / 2 = " << result6 << std::endl;
return 0;
}
Output:
2 + 3 * 4 = 14
(2 + 3) * 4 = 20
10 - 6 / 2 = 7
(10 - 6) / 2 = 2
2 * 3 + 4 * 5 = 26
100 / 5 / 2 = 10
Real-world calculation example
#include <iostream>
#include <iomanip>
int main()
{
// Calculate compound interest: A = P(1 + r/n)^nt
// For simplicity, we'll calculate one year with monthly compounding
double principal = 1000.0; // Initial amount
double annualRate = 0.05; // 5% annual interest rate
int compoundsPerYear = 12; // Monthly compounding
int years = 1;
// Simplified calculation for monthly compounding over 1 year
double monthlyRate = annualRate / compoundsPerYear;
// Calculate month by month
double amount = principal;
for (int month = 1; month <= compoundsPerYear * years; ++month) {
amount = amount * (1 + monthlyRate);
std::cout << std::fixed << std::setprecision(2);
std::cout << "Month " << month << ": $" << amount << std::endl;
}
std::cout << "\nFinal calculation check:" << std::endl;
double finalAmount = principal * (1 + monthlyRate);
for (int i = 1; i < 12; ++i) {
finalAmount *= (1 + monthlyRate);
}
std::cout << "Final amount: $" << finalAmount << std::endl;
std::cout << "Interest earned: $" << (finalAmount - principal) << std::endl;
return 0;
}
Output:
Month 1: $1004.17
Month 2: $1008.35
Month 3: $1012.55
Month 4: $1016.77
Month 5: $1021.01
Month 6: $1025.26
Month 7: $1029.53
Month 8: $1033.82
Month 9: $1038.13
Month 10: $1042.45
Month 11: $1046.79
Month 12: $1051.16
Final calculation check:
Final amount: $1051.16
Interest earned: $51.16
Common arithmetic operator pitfalls
1. Integer division truncation
#include <iostream>
int main()
{
// ❌ Unexpected integer division
int score = 85;
int total = 100;
double percentage = score / total * 100; // 0 * 100 = 0 (wrong!)
// ✅ Correct floating-point division
double correctPercentage = static_cast<double>(score) / total * 100;
std::cout << "Wrong percentage: " << percentage << "%" << std::endl;
std::cout << "Correct percentage: " << correctPercentage << "%" << std::endl;
return 0;
}
Output:
Wrong percentage: 0%
Correct percentage: 85%
2. Operator precedence confusion
#include <iostream>
int main()
{
// ❌ Misleading expression - what's the intention?
int result1 = 10 - 2 * 3; // 10 - 6 = 4 (multiplication first)
// ✅ Clear intention with parentheses
int result2 = (10 - 2) * 3; // 8 * 3 = 24
int result3 = 10 - (2 * 3); // 10 - 6 = 4
std::cout << "Confusing: 10 - 2 * 3 = " << result1 << std::endl;
std::cout << "Clear intention 1: (10 - 2) * 3 = " << result2 << std::endl;
std::cout << "Clear intention 2: 10 - (2 * 3) = " << result3 << std::endl;
return 0;
}
Output:
Confusing: 10 - 2 * 3 = 4
Clear intention 1: (10 - 2) * 3 = 24
Clear intention 2: 10 - (2 * 3) = 4
3. Overflow and underflow
#include <iostream>
#include <climits>
int main()
{
// Integer overflow
int maxInt = INT_MAX;
std::cout << "Maximum int: " << maxInt << std::endl;
// This will overflow!
int overflow = maxInt + 1;
std::cout << "Overflow result: " << overflow << std::endl;
// Multiplication overflow
int large1 = 100000;
int large2 = 30000;
int product = large1 * large2; // May overflow on some systems
std::cout << "Large multiplication: " << large1 << " * " << large2 << " = " << product << std::endl;
// Safe way with larger type
long long safeProduct = static_cast<long long>(large1) * large2;
std::cout << "Safe multiplication: " << safeProduct << std::endl;
return 0;
}
Output:
Maximum int: 2147483647
Overflow result: -2147483648
Large multiplication: 100000 * 30000 = -1539607552
Safe multiplication: 3000000000
Best practices for arithmetic operators
1. Be explicit about integer vs. floating-point division
// ❌ Unclear intention
double result = a / b;
// ✅ Clear intention
double result = static_cast<double>(a) / b; // Want floating-point division
int result = a / b; // Want integer division
2. Use parentheses for clarity
// ❌ Relies on precedence knowledge
int result = a + b * c - d / e;
// ✅ Clear and readable
int result = a + (b * c) - (d / e);
3. Check for division by zero
// ✅ Safe division
if (denominator != 0) {
double result = numerator / denominator;
// Use result...
} else {
// Handle division by zero error
}
4. Choose appropriate data types
// ✅ Use the right type for the job
int count = 42; // For counting
double price = 19.99; // For money/measurements
long long population = 7800000000LL; // For very large numbers
5. Watch out for overflow
// ✅ Check for potential overflow
if (a > INT_MAX / b) {
// Use larger type or handle overflow
long long result = static_cast<long long>(a) * b;
} else {
int result = a * b;
}
Summary
Arithmetic operators are fundamental to C++ programming:
The five arithmetic operators:
+
addition-
subtraction (also unary negation)*
multiplication/
division%
remainder (covered in the next lesson)
Key concepts:
- Integer division truncates the result (10 / 3 = 3)
- Floating-point division preserves decimals (10.0 / 3.0 = 3.33333)
- Mixed operations promote integers to floating-point
- Precedence: multiplication and division before addition and subtraction
- Division by zero must be avoided (undefined behavior)
Best practices:
- Use appropriate data types for your calculations
- Be explicit about integer vs. floating-point division
- Use parentheses for clarity in complex expressions
- Check for division by zero before dividing
- Watch out for overflow with large numbers
Understanding these operators and their behavior with different data types is essential for writing correct mathematical calculations in C++.
Quiz
-
What is the result of
7 / 3
when both operands are integers? a) 2.33 b) 2 c) 3 d) Compiler error -
What is the result of
7.0 / 3
? a) 2 b) 2.33333 c) 3 d) Compiler error -
What happens when you divide an integer by zero? a) Result is 0 b) Result is infinity c) Undefined behavior d) Compiler error
-
What is the value of
2 + 3 * 4
? a) 20 b) 14 c) 11 d) 24 -
How can you ensure floating-point division when both operands are integers? a) Use parentheses b) Cast at least one operand to double c) Use a different operator d) Not possible
Practice exercises
Try these exercises to master arithmetic operators:
-
Calculator Program: Create a simple calculator that performs all four basic operations and handles edge cases like division by zero.
-
Unit Converter: Write a program that converts between different units (temperature, distance, weight) using arithmetic operations.
-
Financial Calculator: Build a program that calculates loan payments, compound interest, or investment returns using multiple arithmetic operations.
-
Geometry Calculator: Create functions to calculate areas and volumes of different shapes using arithmetic operators.
Explore More Courses
Discover other available courses while this lesson is being prepared.
Browse CoursesLesson Discussion
Share your thoughts and questions