← C++ from Scratch Lesson 17 of 62 · 10 XP

The while loop

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

while repeats its body as long as the condition is true:

int n = 5;
while (n > 0) {
    std::cout << n << ' ';
    n--;
}
// 5 4 3 2 1

do { … } while (condition); — the body first, then the check: it runs at least once (a menu, "ask again").

A classic is reading until the input ends: while (std::cin >> x) { … }. The expression std::cin >> x is false when there's nothing more to read.

If you forget to change the variable in the condition, you get an endless loop; in the browser the program is stopped after 5 seconds.

Task. Read numbers until the end of the input and print their sum and count, separated by a space.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.