Learning pathOriginal reference
Lesson 12 of 12

Multiple cases and a debugging mindset

Combine the patterns, isolate each case, and test the boundaries that can break your idea.

One case at a time

When input begins with t, that first value counts cases; it is not itself a value to solve. Build a correct single-case solution, then put its input, processing, and output inside an outer loop.

Per-case state belongs inside that loop. Read exactly the data for each case. An extra read steals from the next case; a missing read leaves data behind. Distinguish the test counter from the element counter.

C++23
#include <iostream>

int main() {
    int t = 0;
    std::cin >> t;
    for (int test = 0; test < t; ++test) {
        int n = 0;
        std::cin >> n; // 0 <= n <= 100000.
        int even = 0;
        for (int i = 0; i < n; ++i) {
            int x = 0;
            std::cin >> x;
            if (x % 2 == 0) { ++even; }
        }
        std::cout << even << '\n';
    }
    return 0;
}

Combine small, understandable steps

For a checkout total, multiply price by quantity using safe types, then add the delivery fee only if the item total is below the threshold. At exactly 1000, a rule saying “below 1000” does not apply.

For a class report, update the total and passing count during the same reads, then divide after the loop. For triangle classification, validate first and classify second. A good solution follows the actual order of the problem’s rules.

Find the earliest wrong state

Separate compilation errors, invalid operations, wrong answers, and excessive running time. Read the first useful compiler message; its cause may be on the preceding line. A program that runs without crashing may still perform an invalid operation.

Trace a tiny failing input. Record the counter, condition, and remembered values after each step. Temporary std::cerr output can expose these values, but remove diagnostic output before submission. Fix the cause, then keep the failing input as a regression test.

Choose tests for a reason

Test minimum and maximum inputs, exact thresholds, one-element lists, all-negative maxima, internal digit zeros, and two consecutive cases. For grade boundaries, 49, 50, and 51 answer a more useful question than three unrelated middle values.

If a sum-to-n program resets its total inside the loop, omits n, and prints during every iteration, there are three independent mistakes. Correct initialization, bounds, and output placement separately. Passing a sample is evidence, not a correctness proof.

Pause & predict

Two independent cases should have totals 12 and 3, but the program prints 12 and 15. What is the likely cause?

Choose an answer
Try it yourself

Turn the idea into code

A sum-from-1-to-n solution uses i < n, declares sum = 0 inside the loop, and prints sum inside the loop. Repair all three issues for 0 ≤ n ≤ 10⁶.

Give me a hint

What must be remembered between iterations? Is n included? How many final answers are required?

Show the explained solution

Place the long long sum before the loop, use i <= n, and print once after the loop. For n = 0 the loop does no work and prints 0.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    long long sum = 0;
    for (int i = 1; i <= n; ++i) {
        sum += i;
    }
    std::cout << sum << '\n';
    return 0;
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.