Skip to content

Instantly share code, notes, and snippets.

@itsjohncs
Created February 26, 2014 18:19
Show Gist options
  • Save itsjohncs/9235214 to your computer and use it in GitHub Desktop.
Save itsjohncs/9235214 to your computer and use it in GitHub Desktop.

Functions and Reference Parameters

Code Tracing

Determine the output of the following programs (assuming a using namespace std and #include <iostream> are provided at the top). If there are errors, make reasonable changes to fix the error and then determine the output.

Program 1

int foo(int & a, int & b) {
    a = b + 4;
    return b;
}

int main() {
    int a = 1, b = 2;
    cout << foo(a, b);
    cout << a << b;
}

Program 2

int foo(double & a, double b) {
    double c = a;
    a = c / b;
    return static_cast<int>(c) % static_case<int>(b);
}

int main() {
    int a = 2, b = 3;
    cout << foo(a, b);
    cout << a << b;
}

Program 3

int foo(int & a, int & b) {
    a += b;
    b /= a;

    return a * b;
}

void bar(int & a, int b, int & c) {
    c = foo(a, b);
}

int main() {
    int a = 1, b = 2, c = 3;
    cout << bar(a, b , c);
    cout << bar(a, b , c);
    cout << a << b << c;
}

Program 4

void foo(int & num) {
    for (; num > 0; --num) {
        cout << num << ", ";
    }
}

int main() {
    int a = 4;
    foo(a);
    cout << a << endl;
}

Header Discovery

Determine the header for each of the following function bodies.

Body 1

// What goes here?
{
    a += 3 * b;
}

Body 2

// What goes here?
{
    for (int i = a; i > 0; --i) {
        cout << i * 2 << endl;
    }
    return a;
}

Body 3

// What goes here?
{
    cout << "Enter a number less than 10: ":
    while (true) {
        cin >> num;
        if (num < 10) {
            break
        } else {
            cout << "Try again: "
        }
    }
}
@atkoehler
Copy link

Is program 2 suppose to have 2 errors that you are testing students on fixing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment