Skip to main content

4. Arithmetic Operators

4.1 Basic Arithmetic Operators

Operator Operation Python Example C Example
+ Addition a + b a + b
- Subtraction a - b a - b
* Multiplication a * b a * b
/ Division a / b a / b
% Modulus a % b a % b

4.2 Important Division Differences

Integer Division:

# Python 3
print(7 / 3)   # Output: 2.333...
print(7 // 3)  # Output: 2 (floor division)
// C
printf("%f\n", 7.0 / 3.0);  // Output: 2.333333
printf("%d\n", 7 / 3);      // Output: 2 (integer division)
printf("%f\n", (float)7 / 3); // Output: 2.333333 (type casting)

4.3 Assignment Operators

Operator Equivalent Python C
= Basic assignment x = 5 x = 5;
+= Add and assign x += 3 x += 3;
-= Subtract and assign x -= 3 x -= 3;
*= Multiply and assign x *= 3 x *= 3;
/= Divide and assign x /= 3 x /= 3;
%= Modulus and assign x %= 3 x %= 3;

4.4 Increment and Decrement Operators

Pre-increment vs Post-increment:

int x = 5;
int y, z;

y = ++x;  // Pre-increment: x becomes 6, then y = 6
z = x++;  // Post-increment: z = 6, then x becomes 7

// Equivalent operations:
x = x + 1;  // Same as x++ or ++x when used alone
x += 1;     // Same as above

Python vs C:

Python C
x += 1 x++ or ++x or x += 1
x -= 1 x-- or --x or x -= 1

4.5 Operator Precedence

Priority Operators Associativity
1 (Highest) ++, -- (postfix) Left to right
2 ++, -- (prefix), +, - (unary) Right to left
3 *, /, % Left to right
4 +, - (binary) Left to right
5 (Lowest) =, +=, -=, etc. Right to left