A girl and a robot thinking together

Let’s think it through · Start with a story

There are three candies in a jar. A robot takes one each time until the jar is empty. It does not need to write out the candy-taking step three times in advance.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Check3 remain; take one
  2. Update2 remain; check again
  3. Update1 remains; check again
  4. 0 remainCondition is false; stop

A while loop checks its condition before each iteration. The loop body usually needs to change related state so the loop can eventually finish.

Here, the state is the number of candies left. Taking one reduces that number by one.

01When is while a good fit?

Some tasks do not have a known number of repetitions in advance.

For example: keep reading numbers as long as the user has not entered 0.

int x;
std::cin >> x;

while (x != 0) {
    std::cout << x << '\n';
    std::cin >> x;
}

02How does while work?

Check the condition→true: run the body↺Go back and check again

If the condition is false from the start, the body does not run even once.

03How is while different from for?

for

Often used for counting or traversing when the update rule is clear.

while

Often used when a task continues “as long as some state remains true.”

Both can express much of the same logic. Choose the form that makes the code clearer.

04Why must the condition change?

int x = 1;

while (x < 10) {
    std::cout << x;
}

Here, x never changes, so the condition remains true and the loop does not finish normally.

05Be careful when input fails

If a loop depends on input, checking only a numeric value may not be enough, because the input itself can fail.

int x;

while (std::cin >> x) {
    std::cout << x << '\n';
}

This loop uses the input stream’s state as its condition. It stops when reading fails or the input ends.

06Can while express a counting loop?

Of course:

int i = 1;

while (i <= 3) {
    std::cout << i << '\n';
    i++;
}

It expresses the same simple repetition as the earlier for loop.

What you have learned

  • A while loop checks its condition before each iteration.
  • It continues while the condition is true and stops when it is false.
  • If the condition is false at the start, the body may not run at all.
  • while is especially useful when the number of repetitions is not known in advance.
  • Think about what change will eventually make the loop stop.

Next: What happens to variables inside a loop?

Your turn

What might happen if the robot takes a candy but forgets to update the recorded number?

Have an answer? Click to see the explanation

The record would keep saying there are candies left, so the condition might stay true and create an infinite loop. The real action and the program’s record both need to be updated.