A while loop is useful when the condition for continuing is the clearest part of your plan. It checks a condition, runs a block if that condition is true, then checks again. The block between braces is called the body.
Here is a countdown for two remaining deliveries:
#include <iostream>
int main() {
int remaining = 2;
while (remaining > 0) {
std::cout << "Delivery " << remaining << '\n';
remaining = remaining - 1;
}
std::cout << "Finished\n";
return 0;
}
The parentheses hold a true-or-false condition, just as they do after if. Unlike if, while returns to that condition after reaching the closing brace. There is no semicolon between the condition and its opening brace.
The output uses '\n', a character literal containing one newline. It moves output to the next line just as the earlier "\n" string literal does. You can also include the escape inside a longer string, as in "Finished\n"; neither form prints a backslash and an n.
The example displays Delivery 2, then Delivery 1, then Finished. When remaining becomes 0, the condition is false and execution continues after the loop. The update belongs inside the body so it happens on every iteration. An update after the loop would be too late to help it stop.
Your starter has a table number but no repetition yet. Keep its initial value at 1 and write the loop at the TODO. Unlike the countdown, this loop moves upward: test table <= 4, display the current table, then add 1. Before running, check that the update is inside the braces. The final update reaches 5, which must fail the next check rather than produce another label.
while loop that prints Table 1 through Table 4, one per line, updating table after each printed label.Edit main.cpp, press Run to inspect the Console, then Submit to check your work.