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:

OperatorNameDescriptionExample
+AdditionAdds two values5 + 2 // 7
-SubtractionSubtracts the second value from the first5 - 2 // 3
*MultiplicationMultiplies two values5 * 2 // 10
/DivisionDivides two values and returns a double5 / 2 // 2.5
~/Integer DivisionDivides two values and returns the integer portion5 ~/ 2 // 2
%ModulusReturns the division remainder5 % 2 // 1
-exprNegationInverts the sign of the value-5

Key Code Examples

Standard Operations

dart
void 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.
dart
void 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 a double.
  • Integer division using ~/ throws away the decimal part and returns an int.
  • Postfix operators apply changes after the expression evaluates; prefix operators apply them before.
WhatsApp