Lesson 12 min
Arithmetic Operators
00:00 / 00:00
Arithmetic Operators
Arithmetic operators in Dart perform common mathematical operations on numeric types (int and double).
List of Arithmetic Operators
Dart supports the following standard mathematical operators:
| Operator | Name | Description | Example |
|---|---|---|---|
+ | Addition | Adds two values | 5 + 2 // 7 |
- | Subtraction | Subtracts the second value from the first | 5 - 2 // 3 |
* | Multiplication | Multiplies two values | 5 * 2 // 10 |
/ | Division | Divides two values and returns a double | 5 / 2 // 2.5 |
~/ | Integer Division | Divides two values and returns the integer portion | 5 ~/ 2 // 2 |
% | Modulus | Returns the division remainder | 5 % 2 // 1 |
-expr | Negation | Inverts the sign of the value | -5 |
Key Code Examples
Standard Operations
dartvoid main() { int a = 10; int b = 3; print(a + b); // 13 print(a - b); // 7 print(a * b); // 30 print(a / b); // 3.3333333333333335 (Returns double) print(a ~/ b); // 3 (Truncated integer division) print(a % b); // 1 (Remainder) }
Prefix vs Postfix Increment/Decrement
Dart has ++ (increment by 1) and -- (decrement by 1) operators. These behave differently depending on where they are placed:
- Postfix (
x++,x--): The current value is used first, and then the variable is modified. - Prefix (
++x,--x): The variable is modified first, and then the new value is used.
dartvoid main() { int x = 5; print(x++); // Prints 5, x becomes 6 print(++x); // x becomes 7, prints 7 int y = 5; print(y--); // Prints 5, y becomes 4 print(--y); // y becomes 3, prints 3 }
Summary
- division using
/always returns adouble. - Integer division using
~/throws away the decimal part and returns anint. - Postfix operators apply changes after the expression evaluates; prefix operators apply them before.