Add and subtract
- C++ course
- Beginner
- Lesson 20/116
- 6 min
Add and test the addition and subtraction functions.
Add and subtract
In the previous lesson you defined the Calculator skeleton; all methods returned 0. Now we will fill add and subtract with real arithmetic.
Inside a method body, the return statement sends the computed value back to the caller. For add you write return a + b;; for subtract write return a - b;.
The method body goes inside { }. A semicolon follows return. This small change makes the calculator actually work.
Method body and return
When a method is called, its body runs top to bottom. The return statement both returns a value and exits the method. Code after return does not run.
Example: calling calc.subtract(10, 3) sets a = 10, b = 3, and return a - b; gives 7. This value goes back to the caller.
The expression std::cout << calc.subtract(10, 3) first calls subtract, takes the returned 7 and prints it. This chaining is a common C++ pattern.
Practice Fill in add and subtract
Change the add method body to return a + b; and the subtract method body to return a - b;. Leave multiply and divide as return 0; for now. The main already calls calc.subtract(10, 3); the output must be 7.
Starter code
#include <iostream>
class Calculator {
public:
double add(double a, double b) { return 0; }
double subtract(double a, double b) { return 0; }
double multiply(double a, double b) { return 0; }
double divide(double a, double b) { return 0; }
};
int main() {
Calculator calc;
// Fill in add and subtract with real arithmetic
std::cout << calc.subtract(10, 3) << std::endl;
return 0;
}Sample solution
#include <iostream>
class Calculator {
public:
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return 0; }
double divide(double a, double b) { return 0; }
};
int main() {
Calculator calc;
// Fill in add and subtract with real arithmetic
std::cout << calc.subtract(10, 3) << std::endl;
return 0;
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add body
double add(double a, double b) { return ____; }
double add(double a, double b) { return a + b; }
Explanation: The add method should return a + b.
2 What should the body of add(double a, double b) return?
- return a + b; Correct answer
- return a;
- return 0;
- return b;
Explanation: The add method returns a + b.
3 Match method concepts
| Term | Meaning |
|---|---|
return a + b; |
Addition result |
return a - b; |
Subtraction result |
calc.subtract(10,3) |
Returns 7 |
{ } |
Method body |