Define a function with two formal arguments and use its return value.
Before the Lab
Week 7: function definitions, declarations, calls, formal and actual arguments, passing by value, return values, and local scope. This lab uses passing by value.
II. Environment
A computer with Windows, macOS, or Linux.
Use OnlineGDB in C++ mode, or the C++ environment demonstrated in class.
Save your program as lab03.cpp. Use one source file for this lab.
Complete the TODOs in the starter code, then compare your result with the expected output. The starter is intentionally unfinished.
Task 1 — Read and run the starter code
Find main() and add(). In the function definition, a and b are formal arguments. In add(first, second), first and second are actual arguments. Run the program and enter 3 5. The starter returns 0 because add() is not finished.
Task 2 — Complete add()
Replace the placeholder return value with the sum of a and b. Keep the input and output code in main().
Task 3 — Test three inputs
Run the program three times: 3 5 should give 8; 0 0 should give 0; -2 7 should give 5.
#include <iostream>
int add(int a, int b) {
// TODO 1: Return the sum of a and b.
return 0;
}
int main() {
int first = 0;
int second = 0;
std::cin >> first >> second;
std::cout << "Sum: " << add(first, second) << '\n';
return 0;
}
Expected Output
Example for input 3 5.
Sum: 8
IV. Submission
Your completed lab03.cpp source file.
One or two screenshots showing your test results.
A short answer to each question below, in English or Chinese.
Two Short Questions
What do a and b receive when add(first, second) is called?