Learning pathOriginal reference
Lesson 7 of 12

While, do-while, and stopping rules

Choose a loop from its stopping condition and read the exact input format.

Repeat while the situation holds

A while loop checks its condition before executing the body, so it can run zero times. If a counter starts at 1 and the condition is i <= 3, update i inside the body so the loop eventually stops.

Every loop needs a progress argument: what changes, and why will it make the condition false or trigger an exit? Missing an update can create endless output even though the code compiles.

A sentinel marks the end of data

If a problem explicitly guarantees a terminating 0, read one value, process it only while it is nonzero, and read again. The sentinel is not data to include. The first input may already be the sentinel.

For at most 100000 values in [−10⁹, 10⁹], the sum fits long long. A count-prefixed list, a sentinel-terminated list, and input until end-of-file are three different formats; never guess which one the judge uses.

C++23
#include <iostream>

int main() {
    long long sum = 0;
    int x = 0;
    std::cin >> x;
    while (x != 0) {
        sum += x;
        std::cin >> x;
    }
    std::cout << sum << '\n';
    return 0;
}

Execute once before checking

A do-while executes the body before checking its condition. With i = 5 and condition i <= 3, it still executes once. The final while(condition); needs a semicolon. This form is useful when even zero needs one processing step, as with decimal digits.

Optional extension: while (std::cin >> x) processes successful reads until extraction fails, including at end-of-file. It also stops on invalid input. Use it only when that matches the stated format, rather than adding an invented sentinel.

Pause & predict

With i initially 5 and condition i <= 3, how many times do while and do-while execute?

Choose an answer
Try it yourself

Turn the idea into code

For a stream of integers ending in 0, count the positive values before the sentinel. At most 100000 data values are given. For -3 5 9 -1 0, print 2.

Give me a hint

A count adds one per match. Read the next value even when the current value is not positive.

Show the explained solution

Keep the input update outside the positivity condition so every iteration advances. The initial sentinel produces a count of zero.

C++23
#include <iostream>

int main() {
    int x = 0, positive = 0;
    std::cin >> x;
    while (x != 0) {
        if (x > 0) { ++positive; }
        std::cin >> x;
    }
    std::cout << positive << '\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.