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.
#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.
With i initially 5 and condition i <= 3, how many times do while and do-while execute?
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.
#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
Mark complete when you can explain it yourself.