Lesson 10: Arithmetic Operators and Expressions
Basic Arithmetic Operators
These operators perform mathematical calculations.
| Operator | Description | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulo (Remainder) | a % b |
Integer Division vs. Floating Point Division
In C, the division operator (/) behaves differently depending on the operands:
-
Integer Division: If both operands are integers, the result is an integer (the fractional part is truncated, not rounded). c int result1 = 10 / 3; // result1 is 3 int result2 = 1 / 2; // result2 is 0
-
Floating Point Division: If at least one operand is a float or double, the result is a float/double. c double result3 = 10.0 / 3; // result3 is 3.333...
Modulo Operator (%)
The modulo operator returns the remainder of an integer division. It is only applicable to integer operands.
c int remainder = 17 % 5; // remainder is 2 (17 = 3*5 + 2)
Operator Precedence
Expressions are evaluated based on precedence (like in mathematics):
- Parentheses
() - Multiplication, Division, Modulo (
*,/,%) - Addition, Subtraction (
+,-)
Operators at the same level of precedence are evaluated left-to-right (associativity).