Learning pathOriginal reference
Lesson 9 of 12

Five patterns worth understanding

Use sums, counts, best-so-far candidates, products, and flags to process a stream.

Sum the values; count the matches

A sum adds the value itself; a count adds one when a condition matches. Both start at zero because no data has been processed. After every iteration, explain exactly what each accumulator represents.

For scores 40, 50, 80, 90, the total is 260 and the number passing at 50 or above is 3. One read can update both. A statement that remains true as the loop advances is called a loop invariant.

C++23
#include <iostream>
#include <iomanip>

int main() {
    int n = 0;
    std::cin >> n; // 1 <= n <= 100000; each score is 0..100.
    long long sum = 0;
    int passed = 0;
    for (int i = 0; i < n; ++i) {
        int score = 0;
        std::cin >> score;
        sum += score;
        if (score >= 50) { ++passed; }
    }
    std::cout << sum << ' ' << passed << '\n';
    std::cout << std::fixed << std::setprecision(2)
              << static_cast<double>(sum) / n << '\n';
    return 0;
}

Start a maximum from a real value

For a nonempty list, read the first actual value into best and compare the remaining n − 1 values with it. Replace best only when the new value is larger. To find a minimum, reverse the comparison.

Zero is not a safe initial maximum: for [−8, −3, −10], it is larger than every input and would give the wrong answer. A one-value list needs no comparisons after reading its first element.

Products start at one

For factorial, start answer at 1 and multiply by 1 through n. The zero-iteration case leaves 0! = 1. Under the source constraint 0 ≤ n ≤ 20, long long is sufficient; 21! exceeds a signed 64-bit integer.

Optional extension: calculate a small a to the power b by multiplying by a exactly b times, beginning at one. This requires b ≥ 0 and bounds that keep every product representable. The ^ symbol is not a power operator.

Flags remember a lasting fact

To remember whether any negative appeared, start found = false and set it to true on a negative. Do not set it back to false on a later nonnegative value: the earlier observation remains true.

Sums, counts, extrema, and flags often need only one value at a time. You do not need an array just because the input has many values. Store a sequence only when you must revisit it later.

Pause & predict

Which initial values match sum, product, and maximum of a guaranteed nonempty list?

Choose an answer
Try it yourself

Turn the idea into code

Read 1 ≤ n ≤ 100000 followed by n values in [−10⁹, 10⁹]. Print their maximum without storing the whole list.

Give me a hint

The first read establishes the candidate. Exactly n − 1 reads remain.

Show the explained solution

After each read, best is the maximum of everything consumed. This uses one running candidate and works for equal values, all-negative values, and n = 1.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    long long best = 0;
    std::cin >> best;
    for (int i = 1; i < n; ++i) {
        long long x = 0;
        std::cin >> x;
        if (x > best) { best = x; }
    }
    std::cout << best << '\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.