Multiply and divide
- Dart course
- Beginner
- Lesson 21/116
- 6 min
Add multiplication, division and the divide-by-zero check.
Multiply and divide
Now we will add multiply and divide functions. Multiplication uses *, division uses /.
Important: in Dart / always returns a double. So divide should return double: double divide(int a, int b) => a / b;.
For integer division you use ~/ (for example 10 ~/ 3 = 3). But in the calculator we want a decimal result, so we use /.
Practice Add multiply and divide
Add the functions int multiply(int a, int b) => a * b; and double divide(int a, int b) => a / b; to the program. Inside main write print(multiply(5, 6)) and print(divide(10, 4)).
Starter code
void main() {
print('Calculator ready');
print(add(3, 4));
print(subtract(10, 3));
// Add calls to multiply and divide
}
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;
// Write multiply and divide functions hereSample solution
void main() {
print('Calculator ready');
print(add(3, 4));
print(subtract(10, 3));
print(multiply(5, 6));
print(divide(10, 4));
}
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;
int multiply(int a, int b) => a * b;
double divide(int a, int b) => a / b;Expected output
Calculator ready 7 7 30 2.5
Divide-by-zero check
In division, if b is zero Dart returns Infinity as a double; it does not throw. But this is usually an unwanted result.
In a real calculator you want to prevent division by zero. You can add an if check: if (b == 0) { throw Exception('Divide by zero'); }.
In the next lesson we will see how to catch this thrown error with try/catch. For now, knowing the difference between ~/ and / is enough.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is the integer division operator?
10 ~/ 3 = 3- /
- //
- %
- ~/ Correct answer
Explanation: ~/ does integer division.
2 Integer division
int result = 10 ____ 3;
int result = 10 ~/ 3;
Explanation: ~/ does integer division.
3 Match the operators
| Term | Meaning |
|---|---|
* |
Multiplication |
/ |
Division (double) |
~/ |
Integer division |
% |
Modulo (remainder) |