Table of Contents
- Introduction to Arithmetic Operators
- Basic Arithmetic Operators
- Operator Precedence
- Increment and Decrement Operators
- Compound Assignment Operators
- Unary Operators
- Integer vs Floating-Point Arithmetic
- Modulo Operator
- Exponentiation
- Division by Zero
- Type Conversion and Coercion
- Overflow and Underflow
- Bitwise Operators (Arithmetic Context)
- Language-Specific Examples
- Best Practices
- Common Pitfalls
Introduction to Arithmetic Operators
Arithmetic operators are fundamental building blocks in programming that perform mathematical operations on numeric values. They allow us to manipulate numbers, perform calculations, and implement mathematical logic in our programs.
What Are Arithmetic Operators?
# Arithmetic operators allow us to perform mathematical calculations a = 10 b = 3 sum_result = a + b # Addition difference = a - b # Subtraction product = a * b # Multiplication quotient = a / b # Division (float) integer_quotient = a // b # Integer division remainder = a % b # Modulo (remainder) power = a ** b # Exponentiation
Why Arithmetic Operators Matter
# Real-world applications # 1. Financial calculations price = 19.99 quantity = 5 tax_rate = 0.08 total = price * quantity tax = total * tax_rate final_total = total + tax # 2. Game development score = 100 lives = 3 score += 10 # Add points lives -= 1 # Lose a life # 3. Data processing numbers = [1, 2, 3, 4, 5] total = sum(numbers) # Built-in, but uses addition internally average = total / len(numbers)
Basic Arithmetic Operators
Addition (+)
# Addition in Python a = 5 b = 3 result = a + b # 8 # With floats x = 5.5 y = 2.2 result = x + y # 7.7 # String concatenation (overloaded) greeting = "Hello" + " " + "World" # "Hello World" # List concatenation list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 # [1, 2, 3, 4, 5, 6]
// JavaScript addition let a = 5; let b = 3; let result = a + b; // 8 // Type coercion (string concatenation) let str = "Hello" + " " + "World"; // "Hello World" let mixed = 5 + "3"; // "53" (number to string coercion)
Subtraction (-)
# Subtraction in Python a = 10 b = 3 result = a - b # 7 # Negative numbers negative = 5 - 10 # -5 # With floats x = 10.5 y = 3.2 result = x - y # 7.3
Multiplication (*)
# Multiplication in Python a = 5 b = 3 result = a * b # 15 # With floats x = 2.5 y = 4.0 result = x * y # 10.0 # String repetition (overloaded) stars = "*" * 10 # "**********" # List repetition zeros = [0] * 5 # [0, 0, 0, 0, 0]
// JavaScript multiplication let a = 5; let b = 3; let result = a * b; // 15 // Type coercion let str = "5" * 3; // 15 (string to number) let invalid = "hello" * 3; // NaN
Division (/)
# Division in Python (always returns float) a = 10 b = 3 result = a / b # 3.3333333333333335 # Integer division (floor division) integer_result = a // b # 3 # Negative numbers neg_result = -10 // 3 # -4 (floor, not truncate)
// JavaScript division let a = 10; let b = 3; let result = a / b; // 3.3333333333333335 // Integer division not built-in let intResult = Math.floor(a / b); // 3
Modulo (%)
# Modulo (remainder) in Python a = 10 b = 3 remainder = a % b # 1 # Even/Odd check is_even = 42 % 2 == 0 # True # Cyclic behavior for i in range(12): print(i % 3) # 0,1,2,0,1,2,0,1,2,0,1,2 # Negative numbers (Python) neg_mod = -10 % 3 # 2 (result always positive)
// JavaScript modulo let a = 10; let b = 3; let remainder = a % b; // 1 // Negative numbers (JavaScript) let negMod = -10 % 3; // -1 (sign of dividend)
Operator Precedence
Precedence Rules
# Operator precedence (from highest to lowest) # 1. Parentheses () # 2. Exponentiation ** # 3. Unary +, - # 4. Multiplication *, Division /, Modulo %, Floor division // # 5. Addition +, Subtraction - # Examples result = 2 + 3 * 4 # 14 (multiplication first) result = (2 + 3) * 4 # 20 (parentheses override) result = 2 ** 3 * 2 # 16 (exponentiation first) result = 2 ** (3 * 2) # 64 (parentheses) result = 10 / 2 * 3 # 15.0 (left to right)
// JavaScript precedence (similar) let result = 2 + 3 * 4; // 14 let result2 = (2 + 3) * 4; // 20 let result3 = 10 / 2 * 3; // 15
Associativity
# Left-to-right associativity (most operators) result = 10 / 2 / 2 # 2.5 ((10/2)/2) # Right-to-left associativity (exponentiation) result = 2 ** 3 ** 2 # 512 (2**(3**2))
Increment and Decrement Operators
Prefix vs Postfix
# Python doesn't have ++/-- operators # Using augmented assignment count = 5 count += 1 # Increment count -= 1 # Decrement
// JavaScript increment/decrement let count = 5; // Postfix (returns original value then increments) let postResult = count++; // postResult = 5, count = 6 // Prefix (increments then returns new value) let preResult = ++count; // preResult = 7, count = 7 // Decrement similarly let decPost = count--; // decPost = 7, count = 6 let decPre = --count; // decPre = 5, count = 5
// Java increment/decrement int count = 5; // Postfix int postResult = count++; // postResult = 5, count = 6 // Prefix int preResult = ++count; // preResult = 7, count = 7
Common Use Cases
// Loop counter
for (let i = 0; i < 10; i++) {
console.log(i);
}
// Array iteration
let index = 0;
while (index < array.length) {
process(array[index++]); // Postfix used here
}
Compound Assignment Operators
Syntax and Usage
# Python compound assignments x = 10 x += 5 # x = x + 5 -> 15 x -= 3 # x = x - 3 -> 12 x *= 2 # x = x * 2 -> 24 x /= 4 # x = x / 4 -> 6.0 x //= 2 # x = x // 2 -> 3.0 x %= 2 # x = x % 2 -> 1.0 x **= 3 # x = x ** 3 -> 1.0
// JavaScript compound assignments let x = 10; x += 5; // x = 15 x -= 3; // x = 12 x *= 2; // x = 24 x /= 4; // x = 6 x %= 2; // x = 0 x **= 3; // x = 0
Practical Applications
# Accumulator pattern total = 0 for num in range(1, 101): total += num # Add each number # Running product product = 1 for num in [1, 2, 3, 4, 5]: product *= num # 120 # Counter count = 0 for item in data: if condition(item): count += 1
Unary Operators
Unary Plus and Minus
# Unary operators x = 5 positive = +x # 5 negative = -x # -5 # With expressions result = - (2 + 3) # -5
Unary Plus in Different Languages
// JavaScript - unary plus converts to number let str = "123"; let num = +str; // 123 (converts string to number) let bool = +true; // 1 // Unary minus for conversion let negative = -"456"; // -456
# Python - unary plus does nothing (for symmetry)
num = +"123" # Error! Cannot convert string to int
# Use int() for conversion
num = int("123")
Integer vs Floating-Point Arithmetic
Precision Differences
# Python integer arithmetic (exact)
a = 10
b = 3
int_result = a // b # 3 (floor division)
mod_result = a % b # 1 (remainder)
# Floating-point arithmetic (approximate)
float_result = a / b # 3.3333333333333335
# Floating-point precision issues
sum = 0.1 + 0.2
print(sum) # 0.30000000000000004 (not 0.3)
# Use decimal for precise decimal calculations
from decimal import Decimal
precise = Decimal('0.1') + Decimal('0.2') # Decimal('0.3')
// JavaScript - all numbers are floating-point let result = 10 / 3; // 3.3333333333333335 // Precision issues 0.1 + 0.2 === 0.3; // false // Integer division requires Math.floor let intDiv = Math.floor(10 / 3); // 3
Mixed Type Operations
# Python - type promotion int_val = 5 float_val = 2.5 result = int_val + float_val # 7.5 (float) # Division always returns float result = 10 / 2 # 5.0
// JavaScript - always returns number let result = 10 / 2; // 5 (number) let result2 = 10 / 3; // 3.3333333333333335
Modulo Operator
Basic Modulo Operations
# Python modulo examples print(10 % 3) # 1 print(10 % 5) # 0 (divisible) print(10 % 7) # 3 # Even/Odd check is_even = n % 2 == 0 is_odd = n % 2 == 1 # Wrap-around (cyclic) behavior for i in range(12): print(i % 3, end=' ') # 0,1,2,0,1,2,0,1,2,0,1,2
Practical Applications
# 1. Time calculations
total_seconds = 3665
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
# 2. Circular arrays
array = ['A', 'B', 'C', 'D']
index = 5
value = array[index % len(array)] # 'B' (5 % 4 = 1)
# 3. Pagination
items_per_page = 10
total_items = 95
total_pages = (total_items + items_per_page - 1) // items_per_page # 10
remaining = total_items % items_per_page # 5
# 4. Alternating patterns
for i in range(20):
if i % 2 == 0:
print(f"{i}: Even")
else:
print(f"{i}: Odd")
Negative Modulo Behavior
# Python - result has sign of divisor (always non-negative) print(-10 % 3) # 2 print(10 % -3) # -2 # JavaScript - result has sign of dividend console.log(-10 % 3); // -1 console.log(10 % -3); // 1
Exponentiation
Power Operator
# Python exponentiation result = 2 ** 3 # 8 result = 2 ** 10 # 1024 result = 4 ** 0.5 # 2.0 (square root) # Large exponents big = 2 ** 1000 # Still exact with Python integers # Using pow() function result = pow(2, 3) # 8 result = pow(2, 3, 5) # 2**3 % 5 = 3 (modular exponentiation)
// JavaScript exponentiation let result = 2 ** 3; // 8 let result2 = Math.pow(2, 3); // 8 // Large exponents lose precision let big = 2 ** 1000; // Not exact for large numbers
Practical Applications
# Compound interest principal = 1000 rate = 0.05 # 5% annual interest years = 10 amount = principal * (1 + rate) ** years # 1628.89 # Geometric progression terms = [2 ** i for i in range(10)] # 1,2,4,8,16,32,64,128,256,512 # Scientific calculations from math import exp, e growth = 100 * exp(0.1) # Exponential growth
Division by Zero
Handling Division by Zero
# Python - raises ZeroDivisionError
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Check before division
def safe_divide(a, b):
if b == 0:
return None # or raise exception
return a / b
// JavaScript - returns Infinity or NaN
let result = 10 / 0; // Infinity
let result2 = 0 / 0; // NaN
// Check for safe division
function safeDivide(a, b) {
if (b === 0) {
return null;
}
return a / b;
}
Best Practices
# Always check for zero before division
def calculate_average(numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)
# Use guard clauses
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
Type Conversion and Coercion
Implicit Coercion
// JavaScript - implicit coercion let result = "5" + 3; // "53" (string concatenation) let result2 = "5" - 3; // 2 (numeric conversion) let result3 = "5" * "3"; // 15 (numeric conversion) let result4 = "hello" - 3; // NaN
# Python - no implicit coercion
# "5" + 3 # TypeError! Must explicitly convert
num = int("5") + 3 # 8
str_result = "5" + str(3) # "53"
Explicit Conversion
# Python explicit conversion str_num = "123" int_num = int(str_num) # 123 float_num = float(str_num) # 123.0 int_to_str = str(42) # "42" float_to_int = int(3.9) # 3 (truncates)
// JavaScript explicit conversion let str = "123"; let num = Number(str); // 123 let int = parseInt(str); // 123 let float = parseFloat(str); // 123.0 let str2 = String(42); // "42"
Overflow and Underflow
Integer Overflow
# Python - integers are arbitrary precision large = 2 ** 1000 # No overflow # But other languages have limits # C example (would overflow) # int max = 2147483647; # max++; // Overflow
// C - integer overflow
#include <stdio.h>
#include <limits.h>
int main() {
int max = INT_MAX;
printf("%d\n", max); // 2147483647
max++;
printf("%d\n", max); // -2147483648 (overflow)
return 0;
}
Floating-Point Overflow
# Python - floats can overflow to infinity import sys huge = 1e308 result = huge * 10 # inf # Underflow to zero tiny = 1e-308 result = tiny / 10 # 0.0
// JavaScript - overflow to Infinity let huge = 1e308; let overflow = huge * 10; // Infinity
Bitwise Operators (Arithmetic Context)
Common Bitwise Operations
# Python bitwise operators a = 5 # 0101 binary b = 3 # 0011 binary bitwise_and = a & b # 0001 = 1 bitwise_or = a | b # 0111 = 7 bitwise_xor = a ^ b # 0110 = 6 bitwise_not = ~a # -6 (two's complement) left_shift = a << 1 # 1010 = 10 right_shift = a >> 1 # 0010 = 2
// JavaScript bitwise operators let a = 5; let b = 3; console.log(a & b); // 1 console.log(a | b); // 7 console.log(a ^ b); // 6 console.log(~a); // -6 console.log(a << 1); // 10 console.log(a >> 1); // 2
Practical Applications
# Bitmask operations
READ = 1 # 001
WRITE = 2 # 010
EXECUTE = 4 # 100
# Set permissions
permissions = READ | WRITE # 011 (3)
# Check permission
if permissions & READ:
print("Read allowed")
# Toggle permission
permissions ^= EXECUTE # Toggle execute bit
# Clear permission
permissions &= ~WRITE # Clear write bit
Language-Specific Examples
Python
# Python arithmetic examples
import math
# Basic operations
x = 10
y = 3
print(f"Addition: {x + y}") # 13
print(f"Subtraction: {x - y}") # 7
print(f"Multiplication: {x * y}") # 30
print(f"Division: {x / y}") # 3.3333333333333335
print(f"Floor Division: {x // y}") # 3
print(f"Modulo: {x % y}") # 1
print(f"Exponentiation: {x ** y}") # 1000
# Advanced functions
print(f"Absolute value: {abs(-5)}") # 5
print(f"Power: {pow(2, 3)}") # 8
print(f"Square root: {math.sqrt(16)}") # 4.0
print(f"Floor: {math.floor(3.7)}") # 3
print(f"Ceil: {math.ceil(3.2)}") # 4
print(f"Round: {round(3.14159, 2)}") # 3.14
# Complex numbers
c1 = 2 + 3j
c2 = 1 + 1j
print(f"Complex addition: {c1 + c2}") # (3+4j)
print(f"Complex magnitude: {abs(c1)}") # 3.605551275463989
JavaScript
// JavaScript arithmetic examples
let x = 10;
let y = 3;
console.log(`Addition: ${x + y}`); // 13
console.log(`Subtraction: ${x - y}`); // 7
console.log(`Multiplication: ${x * y}`); // 30
console.log(`Division: ${x / y}`); // 3.3333333333333335
console.log(`Modulo: ${x % y}`); // 1
console.log(`Exponentiation: ${x ** y}`); // 1000
// Type coercion
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (numeric conversion)
console.log(5 + "3"); // "53"
console.log(5 - "3"); // 2
// Infinity and NaN
console.log(1 / 0); // Infinity
console.log(0 / 0); // NaN
console.log(isNaN("hello" - 3)); // true
// Math object
console.log(Math.abs(-5)); // 5
console.log(Math.pow(2, 3)); // 8
console.log(Math.sqrt(16)); // 4
console.log(Math.floor(3.7)); // 3
console.log(Math.ceil(3.2)); // 4
console.log(Math.round(3.5)); // 4
// Random numbers
console.log(Math.random()); // 0-1 random number
console.log(Math.floor(Math.random() * 10) + 1); // 1-10 random
Java
// Java arithmetic examples
public class ArithmeticDemo {
public static void main(String[] args) {
int x = 10;
int y = 3;
System.out.println("Addition: " + (x + y)); // 13
System.out.println("Subtraction: " + (x - y)); // 7
System.out.println("Multiplication: " + (x * y)); // 30
System.out.println("Division: " + (x / y)); // 3
System.out.println("Modulo: " + (x % y)); // 1
// Floating-point division
double z = 10.0;
double result = z / y; // 3.3333333333333335
// Math class methods
System.out.println("Absolute: " + Math.abs(-5)); // 5
System.out.println("Power: " + Math.pow(2, 3)); // 8.0
System.out.println("Square root: " + Math.sqrt(16)); // 4.0
System.out.println("Floor: " + Math.floor(3.7)); // 3.0
System.out.println("Ceil: " + Math.ceil(3.2)); // 4.0
System.out.println("Round: " + Math.round(3.5)); // 4
// Random numbers
int random = (int)(Math.random() * 10) + 1; // 1-10
}
}
C
// C arithmetic examples
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main() {
int x = 10;
int y = 3;
printf("Addition: %d\n", x + y); // 13
printf("Subtraction: %d\n", x - y); // 7
printf("Multiplication: %d\n", x * y); // 30
printf("Division: %d\n", x / y); // 3
printf("Modulo: %d\n", x % y); // 1
// Floating-point
double a = 10.0;
double b = 3.0;
printf("Float division: %f\n", a / b); // 3.333333
// Math functions
printf("Absolute: %d\n", abs(-5)); // 5
printf("Power: %f\n", pow(2, 3)); // 8.000000
printf("Square root: %f\n", sqrt(16)); // 4.000000
printf("Floor: %f\n", floor(3.7)); // 3.000000
printf("Ceil: %f\n", ceil(3.2)); // 4.000000
return 0;
}
Rust
// Rust arithmetic examples
fn main() {
let x = 10;
let y = 3;
println!("Addition: {}", x + y); // 13
println!("Subtraction: {}", x - y); // 7
println!("Multiplication: {}", x * y); // 30
println!("Division: {}", x / y); // 3
println!("Modulo: {}", x % y); // 1
// Floating-point
let a = 10.0;
let b = 3.0;
println!("Float division: {}", a / b); // 3.3333333333333335
// Integer division and remainder (must use same type)
let int_div = x / y; // 3
let remainder = x % y; // 1
// Overflow checking
let max = u32::MAX;
// let overflow = max + 1; // Panic in debug, wraps in release
// Safe arithmetic methods
let (result, overflowed) = max.overflowing_add(1);
println!("Result: {}, Overflowed: {}", result, overflowed); // 0, true
// Wrapping arithmetic
let wrapped = max.wrapping_add(1); // 0
// Saturating arithmetic
let saturated = max.saturating_add(1); // 4294967295
// Checked arithmetic
let checked = max.checked_add(1); // None
}
Best Practices
Use Parentheses for Clarity
# ❌ Unclear precedence result = a + b * c - d / e # ✅ Clear with parentheses result = a + (b * c) - (d / e)
Check for Division by Zero
# ❌ Unsafe division def divide(a, b): return a / b # May raise ZeroDivisionError # ✅ Safe division def safe_divide(a, b): if b == 0: return None return a / b
Handle Floating-Point Precision
# ❌ Direct comparison
if 0.1 + 0.2 == 0.3: # False
pass
# ✅ Use tolerance
tolerance = 1e-10
if abs((0.1 + 0.2) - 0.3) < tolerance:
pass
# ✅ Use Decimal for money
from decimal import Decimal
amount = Decimal('0.1') + Decimal('0.2')
Avoid Magic Numbers
# ❌ Magic numbers
if status == 404:
print("Not Found")
# ✅ Named constants
HTTP_NOT_FOUND = 404
if status == HTTP_NOT_FOUND:
print("Not Found")
Common Pitfalls
Integer Division in Mixed Environments
# Python 3 - division returns float result = 5 / 2 # 2.5 int_result = 5 // 2 # 2 # Be careful when porting from Python 2
// JavaScript - all numbers are floating-point let result = 5 / 2; // 2.5 let intResult = Math.floor(5 / 2); // 2
Floating-Point Precision
# Unexpected precision issues
total = 0
for i in range(10):
total += 0.1
print(total) # 0.9999999999999999
# Use Decimal for precise calculations
from decimal import Decimal
total = Decimal('0')
for i in range(10):
total += Decimal('0.1')
print(total) # 1.0
Overflow in Other Languages
// C - integer overflow
#include <stdio.h>
#include <limits.h>
int main() {
int x = INT_MAX;
printf("%d\n", x + 1); // -2147483648 (overflow)
return 0;
}
Type Coercion Confusion
// JavaScript coercion surprises
console.log(5 + "3"); // "53" (string)
console.log(5 - "3"); // 2 (number)
console.log(5 + +"3"); // 8 (unary plus)
console.log("5" + 3); // "53"
console.log("5" - 3); // 2
console.log("hello" - 3); // NaN
Conclusion
Arithmetic operators are fundamental to programming, enabling mathematical computations and logical operations.
Key Takeaways
- Basic Operators: Addition (+), subtraction (-), multiplication (), division (/), modulo (%), exponentiation (* or ^)
- Operator Precedence: Parentheses highest, then exponentiation, then multiplication/division, then addition/subtraction
- Increment/Decrement: ++ and -- operators in many languages (not Python)
- Compound Assignment: +=, -=, *=, /=, etc.
- Integer vs Float: Understand type promotion and division behavior
- Modulo: Useful for wrap-around, even/odd checks, time calculations
- Exponentiation: Powers, roots, exponential growth
- Precision: Be aware of floating-point limitations
- Overflow: Python handles big integers; other languages need care
- Safety: Always check for division by zero
Operator Summary Table
| Operator | Description | Python | JavaScript | Java |
|---|---|---|---|---|
+ | Addition | ✓ | ✓ | ✓ |
- | Subtraction | ✓ | ✓ | ✓ |
* | Multiplication | ✓ | ✓ | ✓ |
/ | Division | ✓ | ✓ | ✓ |
% | Modulo | ✓ | ✓ | ✓ |
** | Exponentiation | ✓ | ✓ (ES7+) | No |
// | Floor Division | ✓ | No | No |
++ | Increment | No | ✓ | ✓ |
-- | Decrement | No | ✓ | ✓ |
+= | Add/Assign | ✓ | ✓ | ✓ |
-= | Subtract/Assign | ✓ | ✓ | ✓ |
*= | Multiply/Assign | ✓ | ✓ | ✓ |
/= | Divide/Assign | ✓ | ✓ | ✓ |
%= | Modulo/Assign | ✓ | ✓ | ✓ |
**= | Power/Assign | ✓ | ✓ (ES7+) | No |
Best Practices Summary
- Use parentheses for clarity
- Check for division by zero
- Be aware of type coercion in languages like JavaScript
- Use appropriate numeric types (Decimal for money)
- Handle floating-point precision with tolerance
- Use constants instead of magic numbers
- Test edge cases (overflow, underflow, negatives)
Arithmetic operators are the building blocks of computational thinking. Master them in your language of choice to write efficient, correct, and maintainable code!