C++ fundamentals

C++ loops practice

A loop repeats a statement or block while a condition allows it to run. Loops let a program process a sequence, retry an operation, or repeat a calculation without duplicating source lines. C++ provides for, while, and do-while loops. Choose the form that makes the number of repetitions and the stopping rule clear.

Use a for loop for counted work

A for loop puts its initialization, continuation condition, and update expression in one place. The initializer runs once. Before each iteration, C++ checks the condition. After the loop body finishes, C++ runs the update expression and checks again. If the condition is false before the first check, the body runs zero times.

Counted loops often start an index at zero and continue while it is less than a count. This pattern processes exactly the number of items in a collection. A condition that uses less-than-or-equal usually adds one iteration. That error is called an off-by-one error because the loop crosses a boundary by one position.

#include <iostream>

int main() {
    int total = 0;
    for (int number = 1; number <= 5; ++number) {
        total += number;
    }
    std::cout << total << '\n';
    return 0;
}

Expected output:

15

The loop begins at one, includes five, then stops when number becomes six. The increment expression runs after each body, including the iteration where number is five. A descriptive loop variable helps readers see what the count represents.

Use while for a condition

A while loop checks its condition before every iteration. It fits work where the stopping point depends on changing state rather than a predetermined count. A program might continue while a queue has items or while a user has not entered a sentinel value. Make sure the body changes state so the condition can eventually become false.

A do-while loop checks its condition after the body. It always runs at least once, which helps when the program must display a prompt before checking whether the user wants another attempt. Its syntax ends with a semicolon after the condition. Omitting that semicolon is a syntax error.

#include <iostream>

int main() {
    int countdown = 3;
    do {
        std::cout << countdown << '\n';
        --countdown;
    } while (countdown > 0);
    return 0;
}

Expected output:

3
2
1

The body prints before the condition checks the new value. When the counter reaches zero, the condition is false and the loop stops. If the condition had started false, a while body would not run, but this do-while body still runs once.

Control a loop with break and continue

break exits the nearest enclosing loop immediately. Use it when the loop has found what it needs or has reached a clear termination marker. The program continues with the statement after the loop. A break does not exit every nested loop; it exits only the innermost one.

continue skips the rest of the current iteration. In a for loop, control then runs the update expression before checking the condition again. In a while loop, control returns to the condition. Ensure your update still happens when using continue; otherwise a counted loop can repeat forever.

Use these statements when they make a stopping rule clearer. A loop condition often communicates the rule better than a break hidden deep in the body. Avoid several exits that make it difficult to tell which state the program leaves behind.

Exercise

Read integers until the input contains zero. Ignore negative values, and print the sum of the positive values read before zero. Sample input:

3 -2 5 0 8

Expected output:

8

Hint 1: Use a while loop that stops when the value is zero. Hint 2: Use continue for negative values.

Show one possible solution
#include <iostream>

int main() {
    int value = 1;
    int total = 0;
    while (std::cin >> value) {
        if (value == 0) {
            break;
        }
        if (value < 0) {
            continue;
        }
        total += value;
    }
    std::cout << total << '\n';
    return 0;
}

Keep learning with CppPath

Continue with the do-while Loops lesson. The full lesson includes a quiz and a checked coding challenge with a free account.