Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Loops and iteration in C++

Loops repeat statements. Learn the differences between while, do ... while, classic for, and range-based for, and how break, continue, and references affect iteration.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

while (condition) { statements; }
do { statements; } while (condition);
for (initialization; condition; update) { statements; }
for (declaration : range) { statements; }

A loop repeatedly executes a statement; one pass is an iteration. while tests its condition before each execution of the body, so the body may never execute. do ... while tests after the body, so once the loop is entered its body executes at least once. A semicolon is required after the final while (condition).

A classic for performs initialization once, then repeats: condition test, body, and update. An omitted condition means true. A variable declared in the initialization is available inside the loop but not after it. Ensure progress toward termination and correct bounds, such as i < count for zero-based indices.

A range-based for visits the elements of an array or another supported range. For an array of integers, auto value creates a copy of an element, auto& value allows modifying the element, and const auto& value allows reading without copying or modifying through that reference. Do not assume that every structural change to a container during iteration is safe.

break terminates the nearest enclosing loop or switch. continue skips the remainder of the current iteration of the nearest loop: in a classic for, the update runs before the condition test; in while and do ... while, control goes to the test. In the example, skipping 3 produces the sum 12, and a reference doubles the elements of values.

The example uses syntax available in C++23. The source is an evolving working draft, not a frozen C++23 publication. The -std=c++23 setting specifies the requested compiler mode; it does not attest to production-runtime behavior.

Examples

#include <iostream>

int main() {
    int sum = 0;
    for (int i = 1; i <= 5; ++i) {
        if (i == 3) {
            continue;
        }
        sum += i;
    }

    int values[] = {2, 4, 6};
    for (int& value : values) {
        value *= 2;
    }

    std::cout << sum << '\n';
    for (const int& value : values) {
        std::cout << value << '\n';
    }
}

Result

12
4
8
12

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources