Add and subtract
- Dart course
- Beginner
- Lesson 20/116
- 6 min
Add and test the addition and subtraction functions.
Addition and subtraction functions
Now we will add two functions: add and subtract. Each takes two ints and returns an int.
In Dart a function is written as return_type name(parameters) { ... }. Example: int add(int a, int b) { return a + b; }.
For short single-line functions you can use the arrow (=>): int add(int a, int b) => a + b;. Both are the same.
Calling functions
You call the functions you defined inside main. Example: print(add(3, 4));. This prints the result of add(3, 4) (7) to the screen.
You can make multiple calls. print(add(3, 4)); and print(subtract(10, 3)); on separate lines give different results.
Functions prevent code repetition. If you add in five places, you call add five times; the addition logic stays in one place.
Practice Add add and subtract
Add the functions int add(int a, int b) => a + b; and int subtract(int a, int b) => a - b; to the program. Inside main write print(add(3, 4)) and print(subtract(10, 3)).
Starter code
void main() {
print('Calculator ready');
// Add calls to add and subtract
}
// Write add and subtract functions hereSample solution
void main() {
print('Calculator ready');
print(add(3, 4));
print(subtract(10, 3));
}
int add(int a, int b) => a + b;
int subtract(int a, int b) => a - b;Expected output
Calculator ready 7 7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a correct Dart function definition?
int add(int a, int b)- add(a, b) { }
- func add(int a, int b) { }
- int add(int a, int b) { } Correct answer
- def add(a, b):
Explanation: Return type + name + parameters + block.
2 Second parameter
int add(int a, ____ b) => a + b;
int add(int a, int b) => a + b;
Explanation: Both parameters are int.
3 Function concepts
| Term | Meaning |
|---|---|
add |
Addition |
subtract |
Subtraction |
int |
Return type |
=> |
Arrow |