Chapter 2 · Functions and Files
Practice · Chapter 2

Functions and Files

Short drills to make the concepts stick — predict what code prints, fix a broken snippet, or write a small function. Commit to an answer before you run anything.

2.4 — Introduction to Function Parameters and Arguments

predict

Does modifying a parameter change the caller's variable?

Arguments are passed by value in C++. Commit to an answer before moving on.

C++
#include <iostream>

void doubleIt(int x)
{
    x = x * 2;
}

int main()
{
    int n{ 5 };
    doubleIt(n);
    std::cout << n << '\n';
    return 0;
}
Choose the output
write

Implement sumOfSquares(a, b)

Write a function that returns the sum of the squares of its two integer parameters.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

2.3 — Void Functions (Non-Value-Returning Functions)

predict

What happens when you stream a void function's result?

A void function has no return value. What does trying to print its result do?

C++
#include <iostream>

void printGreeting()
{
    std::cout << "Hello\n";
}

int main()
{
    std::cout << printGreeting() << '\n';
    return 0;
}
Choose the output

2.2 — Function Return Values (Value-Returning Functions)

fix

Fix the missing computation in scaledSum()

The function is supposed to return (a + b) * scale, but all the tests fail. Find and fix the return statement.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

fix

Fix the integer-division bug in average()

The function declares double as its return type but still truncates results. Find the one-character fix.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.