1. Goals
Repeat an operation with
whileorforand a clear stopping condition.Use counters and accumulators to summarize results.
Distinguish
breakfromcontinueand find loops that run once too often or too rarely.
2. Prerequisites
You know int variables, addition, comparisons, and if statements with {} blocks.
You can compile a program containing main and use std::cout.
This lesson uses small, fixed numbers; arrays, strings, and user-defined functions are not needed.
3. Explanation
Repeat until a condition is false
while (condition) { ... } checks its condition before each iteration. If true,
the loop body runs; if false, execution continues after the loop. If the condition
is false initially, the body never runs. The countdown starts at remaining = 3,
prints the current value, and subtracts 1. At zero, remaining > 0 becomes false.
--remaining decreases the variable by 1; ++day increases it by 1. Here, each
update stands alone rather than being combined with another calculation.
With while, check whether every possible branch brings the program closer
to its stopping point. If you forget to decrease remaining, the condition
never changes and the program keeps repeating.
Repeat with a counter
for (int day = 1; day <= 5; ++day) has three parts:
int day = 1runs once to create the counter.day <= 5is checked before every iteration.++dayruns after each normal iteration, followed by another condition check.
The body sees day equal to 1, 2, 3, 4, and 5: five iterations.
For counting from zero, the corresponding condition is day < 5, with values
from 0 through 4. Do not mix one convention's starting value with the other's ending condition.
A counter increases when an event happens, such as ++issued for each issued ticket.
An accumulator keeps a running total: total += day means total = total + day.
Initialize the total to zero before the loop; putting that declaration inside
resets it every iteration. Selling 1 through 5 tickets across five days gives
1 + 2 + 3 + 4 + 5 = 15 tickets in total.
Skip an iteration or stop early
continue skips the rest of the current iteration. In a for loop, the update
still runs before the next condition check. break exits the nearest enclosing
loop or switch. In the example below, it exits the for loop.
The example skips ticket 3 and stops upon reaching ticket 5, issuing only 1, 2, and 4.
Because break comes before the issue statement, ticket 5 is not issued.
In a while loop, continue returns to the condition check. If the update comes
after continue, that update is skipped and the loop might never terminate.
The for update rule is described in the C++ working draft.
4. Runnable example
Save this program as main.cpp. Its three loops demonstrate independent tasks:
a countdown, a five-day ticket total, and issuing numbered tickets.
For the last loop, the example's policy is to skip number 3 and close before number 5.
#include <iostream>
int main() {
int remaining = 3;
std::cout << "Countdown:";
while (remaining > 0) {
std::cout << ' ' << remaining;
--remaining;
}
std::cout << '\n';
int total = 0;
for (int day = 1; day <= 5; ++day) {
total += day;
}
std::cout << "Total tickets: " << total << '\n';
int issued = 0;
for (int ticket = 1; ticket <= 6; ++ticket) {
if (ticket == 3) {
continue;
}
if (ticket == 5) {
break;
}
++issued;
std::cout << "Issued ticket: " << ticket << '\n';
}
std::cout << "Issued count: " << issued << '\n';
return 0;
}Compile with g++ -std=c++17 -Wall -Wextra -pedantic main.cpp -o lesson.
Run ./lesson on Linux/macOS or .\lesson.exe in Windows PowerShell.
Output:
Countdown: 3 2 1
Total tickets: 15
Issued ticket: 1
Issued ticket: 2
Issued ticket: 4
Issued count: 3' ' is a space character that keeps the countdown numbers separate.
The day variable is declared in the for header and can only be used inside that loop.
The total variable is outside the loop because its result must be kept and printed afterward.
5. Common mistakes
Using
<=when starting at zero and wanting five iterations: 0 through 5 is six iterations.Forgetting to update a
whilecontrol variable, or moving it in the wrong direction.Declaring
int total = 0inside the body and expecting it to retain earlier iterations' totals.Placing
;immediately afterwhile (...)orfor (...): this creates an unintended empty body.Expecting
continueto exit the loop; it only skips the rest of the current iteration.Choosing a huge bound that makes the total exceed the range of
int. For these exercises, keep the day count between 0 and 100; programs accepting input must check this range.
6. Practice
Set
remaining = 0. Confirm that the first line contains onlyCountdown:with no numbers. Then tryremaining = 1to check the single-iteration case.Add
int days = 10before the summation loop and useday <= days. Confirm a total of 55; changingdaysto 0 gives 0, and changing it to 1 gives 1.Keep skipping ticket 3 but stop at ticket 6 instead of 5. Write down the issued ticket numbers and count before running. Expect tickets 1, 2, 4, and 5, with a count of 4.
7. Self-check
How many times does
for (int i = 0; i < 4; ++i)run its body, and with which values? Answer: Four times, withiequal to 0, 1, 2, and 3. At 4, the condition is false.In the example, what happens after
continueat ticket 3? Answer: The remaining issue statements are skipped,++ticketruns, the condition is checked, and ticket 4 is considered.If
int total = 0moves inside the summation loop's body, does it still accumulate? Answer: No. It is recreated as zero each time, and the print statement outside cannot access it. Keep it before the loop to accumulate and use the result afterward.
Sample code
Source file
cpp98_foundation/04_loops/main.cpp
#include <iostream>
int main() {
int remaining = 3;
std::cout << "Countdown:";
while (remaining > 0) {
std::cout << ' ' << remaining;
--remaining;
}
std::cout << '\n';
int total = 0;
for (int day = 1; day <= 5; ++day) {
total += day;
}
std::cout << "Total tickets: " << total << '\n';
int issued = 0;
for (int ticket = 1; ticket <= 6; ++ticket) {
if (ticket == 3) {
continue;
}
if (ticket == 5) {
break;
}
++issued;
std::cout << "Issued ticket: " << ticket << '\n';
}
std::cout << "Issued count: " << issued << '\n';
return 0;
}