While Loop

A for loop is best when you know how many times to repeat. Sometimes you do not know that. You only know when to stop. For this, use a while loop. It repeats its body as long as its condition is true.

How many times must you double 5 to get past 100? This program finds out:

#include <iostream>
using namespace std;

int main() {
    int amount = 5;
    int doublings = 0;
    while (amount < 100) {
        amount = amount * 2;
        doublings++;
    }
    cout << "Amount: " << amount << "\n";
    cout << "Doublings: " << doublings << "\n";
    return 0;
}

Output:

Amount: 160
Doublings: 5

The loop follows simple steps. Check the condition. If it is true, run the body, then check again. If it is false, the loop ends and the program goes on after it.

Here amount went 5, 10, 20, 40, 80, 160. Then 160 < 100 was false, so the loop stopped after 5 rounds. You did not have to know the number 5 in advance. The loop found it.

The condition is checked first

C++ checks the condition before the first round too. If it is false from the start, the body never runs:

int amount = 200;
int doublings = 0;
while (amount < 100) {
    amount = amount * 2;
    doublings++;
}
cout << "Doublings: " << doublings << "\n";

Output:

Doublings: 0

A loop that never ends

Something in the body must change the condition, so that it becomes false one day. Here, amount = amount * 2 does that job. Look at this loop:

int amount = 5;
int doublings = 0;
while (amount < 100) {
    doublings++;
}

Nothing in the body changes amount. It stays 5, the condition stays true, and the loop runs forever. This is called an infinite loop. When you run a program like this here, the code runner stops it after about 5 seconds with a "Time limit exceeded" message. If the loop also prints something in every round, you see "Output limit exceeded" instead, because the output grows too big.

Each time you write a while loop, ask yourself: which line in the body moves the loop toward its end?

In the exercise, count down to 1 with a while loop. Make sure the number changes in each round.