All lessons

4. Loops

while loops

0 of 5 activities0%

Reading 1

Check, then run

Open

while (condition) { body } evaluates the condition first. If it is true, the body runs, then the condition is checked again.

You must update something inside the loop that can eventually make the condition false — otherwise you get an infinite loop.

while is a good fit when you do not know the count in advance.

int n = 3;
while (n > 0) {
    cout << n << endl;
    n--;
}

Check 2

Zero times

Open

If the while condition is false the first time, how many times does the body run?

Fill in 3

Keyword

Open

The loop that checks a condition before each pass is named

Try it 4

Countdown

Open

Run the countdown. Change the starting value.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Sum until zero

Open

Read integers one by one until you read a 0. Print the sum of the numbers before the 0 (do not include 0). Assume there is at least one number before 0.

main.cpp
Loading editor…