Chapter 6 · Operators
Practice · Chapter 6

Operators

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.

6.2 — Arithmetic operators

predict

Integer division into a double

What does this program print? Commit to an answer before reasoning through it.

C++
#include <iostream>

int main()
{
    int numerator   { 3 };
    int denominator { 4 };

    double result = numerator / denominator;

    std::cout << result << '\n';

    return 0;
}
Choose the output
write

Write clampedPercentage

Implement clampedPercentage(covered, total): return coverage as a percentage in [0.0, 100.0], or 0.0 when total <= 0. Watch out for integer division.

student.cppeditable

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

6.3 — Remainder and Exponentiation

predict

Remainder and negative numbers

Both a and b test whether x is odd. What does this print?

C++
#include <iostream>

int main()
{
    int x { -7 };

    bool a { (x % 2) == 1  };
    bool b { (x % 2) != 0  };

    std::cout << a << ' ' << b << '\n';

    return 0;
}
Choose the output
fix

Fix the oddness test for negative numbers

The function returns wrong results for negative odd numbers. Fix it so all tests pass.

student.cppeditable

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

6.4 — Increment/decrement operators, and side effects

predict

Prefix vs postfix: what value is captured?

Trace x carefully through both increments. What does this print?

C++
#include <iostream>

int main()
{
    int x { 10 };
    int a { x++ };
    int b { ++x };

    std::cout << a << ' ' << b << '\n';

    return 0;
}
Choose the output

6.7 — Relational operators and floating point comparisons

fix

Fix floating-point equality

The function ignores its epsilon parameter entirely. Fix it so 0.1 + 0.2 compares equal to 0.3 within the given tolerance.

student.cppeditable

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