โ† All C++ lessons

C++ / Chapter 03

Loops & Repeated Work

Repeat tasks safely with while, do-while, and for loops; trace loop state; build nested patterns; and control iteration deliberately.

Chapter roadmap

Repeat tasks safely with while, do-while, and for loops; trace loop state; build nested patterns; and control iteration deliberately. Work through the concepts in order, type every example yourself, and keep a short debugging log that records predictions, errors, fixes, and what each fix taught you.

Learning objectives

  • Select an appropriate loop
  • Trace initialization, condition, and update
  • Use break and continue sparingly
  • Build nested loops and accumulators

03.1

while and sentinel loops

A while loop checks its condition before every iteration. It fits tasks whose repetition count is unknown, such as reading values until a sentinel appears. The loop must make progress toward termination; otherwise it becomes infinite.

Before running the example, trace each expression and write down the expected state or result. Then run it, compare the actual result, and change one input or rule to confirm that you understand which part controls the behavior.

Example
int value;
int sum = 0;
std::cin >> value;
while (value != -1) {
    sum += value;
    std::cin >> value;
}
std::cout << "Sum: " << sum;
Result
5 8 2 -1
Sum: 15
Check your understanding

Explain the example in plain language, identify one boundary or failure case, and revise it so the output changes in a predictable way.

03.2

do-while and menu repetition

A do-while loop runs its body once before checking the condition. It is useful for menus and prompts that must appear at least once. Keep the condition close to the user decision so the exit behavior is obvious.

Before running the example, trace each expression and write down the expected state or result. Then run it, compare the actual result, and change one input or rule to confirm that you understand which part controls the behavior.

Example
char again;
do {
    std::cout << "Running task...\n";
    std::cout << "Again? (y/n): ";
    std::cin >> again;
} while (again == 'y');
Result
Running task...
Again? (y/n): n
Check your understanding

Explain the example in plain language, identify one boundary or failure case, and revise it so the output changes in a predictable way.

03.3

for loops, counters, and accumulators

A for loop places initialization, condition, and update in one header. Counters track how many times something occurs; accumulators combine values such as totals, products, minimums, and maximums. Off-by-one errors are prevented by writing the intended first and last values before coding.

Before running the example, trace each expression and write down the expected state or result. Then run it, compare the actual result, and change one input or rule to confirm that you understand which part controls the behavior.

Example
int total = 0;
for (int n = 1; n <= 5; ++n) {
    total += n;
}
std::cout << total;
Result
15
Check your understanding

Explain the example in plain language, identify one boundary or failure case, and revise it so the output changes in a predictable way.

03.4

Nested loops and control statements

A nested loop completes all inner iterations for each outer iteration. This structure creates grids, tables, and patterns. break exits the nearest loop and continue skips to its next iteration; both are clearest when used for a small, obvious rule.

Before running the example, trace each expression and write down the expected state or result. Then run it, compare the actual result, and change one input or rule to confirm that you understand which part controls the behavior.

Example
for (int row = 1; row <= 4; ++row) {
    for (int col = 1; col <= row; ++col) {
        std::cout << "*";
    }
    std::cout << "\n";
}
Result
*
**
***
****
Check your understanding

Explain the example in plain language, identify one boundary or failure case, and revise it so the output changes in a predictable way.

Chapter assignments

Complete these in order. Later assignments assume that earlier skills are working. Do not only test the sample values; design tests that challenge boundaries, missing values, incorrect types, empty collections, and other likely failures.

  1. A3.1

    Print multiples of 3 from 3 through 300 and report their count and sum.

    Submit readable source code, a brief design note, and evidence from at least three tests including one boundary or invalid case.

  2. A3.2

    Read positive prices until -1, then report count, total, average, lowest, and highest price.

    Submit readable source code, a brief design note, and evidence from at least three tests including one boundary or invalid case.

  3. A3.3

    Build a validated menu that repeats until the user chooses quit and counts how often each option was selected.

    Submit readable source code, a brief design note, and evidence from at least three tests including one boundary or invalid case.

  4. A3.4

    Use nested loops to print a labeled multiplication table from 1 through 12.

    Submit readable source code, a brief design note, and evidence from at least three tests including one boundary or invalid case.

Chapter project

Number Guessing Tournament

Number Guessing Tournament โ€” Generate a secret number, accept validated guesses, report higher or lower, count attempts, and allow repeated rounds. Maintain wins, total guesses, and best score across the session.

Required process

  1. Write a short specification listing inputs, outputs, rules, and failure cases.
  2. Break the work into small functions, queries, modules, or classes appropriate to the language.
  3. Build the smallest working version before adding optional features.
  4. Test normal, boundary, empty, and invalid cases and record the results.
  5. Refactor names and duplication, then write a concise user guide.

Key terms

  • iteration
  • sentinel
  • counter
  • accumulator
  • infinite loop
  • off-by-one
  • nested loop
  • iteration variable