Chapter 8 · Control Flow
Practice · Chapter 8

Control Flow

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.

8.6 — Switch fallthrough and scoping

predict

What does this switch print?

Trace the execution carefully — pay attention to which break statements are present and which are absent.

C++
#include <iostream>

int main()
{
    int n { 2 };
    switch (n)
    {
    case 1:
        std::cout << "one\n";
        break;
    case 2:
        std::cout << "two\n";
        // no break here
    case 3:
        std::cout << "three\n";
        break;
    default:
        std::cout << "other\n";
        break;
    }
    return 0;
}
Choose the output

8.11 — Break and continue

predict

What does this loop print?

Focus on what happens to the loop counter when continue fires inside a for loop.

C++
#include <iostream>

int main()
{
    for (int i { 1 }; i <= 5; ++i)
    {
        if (i == 3)
            continue;
        std::cout << i << ' ';
    }
    std::cout << '\n';
    return 0;
}
Choose the output

8.8 — Introduction to loops and while statements

fix

Fix the digit-sum loop

The function should return the sum of all decimal digits of n, but it gives wrong answers for some inputs. Find and fix the off-by-one in the loop condition.

student.cppeditable

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

8.9 — Do while statements

fix

Fix the wrong loop kind

The function should return "liftoff" when called with 0, but it doesn't. The bug is in the choice of loop — pick the one whose condition is tested *before* the body runs.

student.cppeditable

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

8.5 — Switch statement basics

write

Implement hintText with switch

Write hintText using a switch statement. Map -1 to "too low", 0 to "correct", 1 to "too high", and any other value to "invalid" via the default case.

student.cppeditable

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