Dart Arithmetic Operators


Arithmetic operators in Dart are used to perform basic mathematical operations on numeric values. These operators allow you to manipulate integers and floating-point numbers easily. Here’s a detailed overview of the arithmetic operators available in Dart:

Arithmetic Operators in Dart

  1. Addition (+)
  2. Subtraction (-)
  3. Multiplication (*)
  4. Division (/)
  5. Integer Division (~/)
  6. Modulus (%)

1. Addition (+)

  • Description: Adds two numbers together.
  • Usage: Can be used with both int and double types.

Example:

void main() { int a = 5; int b = 3; double c = 2.5; print('Addition of a and b: ${a + b}'); // Output: 8 print('Addition of a and c: ${a + c}'); // Output: 7.5 }

2. Subtraction (-)

  • Description: Subtracts the second number from the first.
  • Usage: Can also be used with both int and double types.

Example:

void main() { int a = 5; int b = 3; print('Subtraction of a and b: ${a - b}'); // Output: 2 }

3. Multiplication (*)

  • Description: Multiplies two numbers.
  • Usage: Applicable to both int and double types.

Example:

void main() { int a = 5; int b = 3; print('Multiplication of a and b: ${a * b}'); // Output: 15 }

4. Division (/)

  • Description: Divides the first number by the second. This operator always returns a double, even if both operands are integers.
  • Usage: Suitable for both int and double types.

Example:

void main() { int a = 5; int b = 2; print('Division of a by b: ${a / b}'); // Output: 2.5 }

5. Integer Division (~/)

  • Description: Performs integer division, which divides and returns the quotient without the remainder. The result is an int.
  • Usage: Can be used with both int types.

Example:

void main() { int a = 5; int b = 2; print('Integer division of a by b: ${a ~/ b}'); // Output: 2 }

6. Modulus (%)

  • Description: Returns the remainder of the division of the first number by the second.
  • Usage: Applicable to both int and double types.

Example:

void main() { int a = 5; int b = 2; print('Remainder of a divided by b: ${a % b}'); // Output: 1 }

Summary of Arithmetic Operators

OperatorDescriptionExample
+Addition5 + 3 (results in 8)
-Subtraction5 - 3 (results in 2)
*Multiplication5 * 3 (results in 15)
/Division5 / 2 (results in 2.5)
~/Integer Division5 ~/ 2 (results in 2)
%Modulus (Remainder)5 % 2 (results in 1)

Conclusion

Arithmetic operators in Dart provide a straightforward way to perform mathematical calculations. Whether you're adding, subtracting, multiplying, or dividing, these operators are essential for manipulating numerical data in your Dart programs. Understanding how to use these operators effectively is crucial for developing robust applications and handling numeric computations.