C++ Programming

WEEK 8 · LAB 3

Lab 3 — Functions

Add two numbers with a function.

I. Objectives

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

Open OnlineGDB ↗

III. Tasks and Requirements

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.

Starter Code

Download .cpp
#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

Two Short Questions

  1. What do a and b receive when add(first, second) is called?
  2. What value does return send back to main()?