C++ Loops

for Loop

Use when you know how many times to repeat a block of code

Basic Structure

for (initialization; condition; update) {
    // code block
}

Example

for (int i = 0; i < 5; i++) {
    cout << i << " ";
}

while Loop

Use when the condition is checked before entering the loop

Basic Structure

Here is this general structure of a while loop in a kotlin program.

while (condition) {
    // code block
}

Example

int i = 0;
while (i < 5) {
    cout << i << " ";
    i++;
}

do-while Loop

Executes at least once, then checks the condition

Basic Structure

do {
    // code block
} while (condition)

Example

int i = 0;
do {
    cout << i << " ";
    i++;
} while (i < 5);

break Statement

break exits the loop immediately:

for (int i = 0; i < 10; i++) {
    if (i == 5) break;
    cout << i << " ";
}

continue Statement

continue skips the rest of the loop body and goes to the next iteration:

for (int i = 0; i < 5; i++) {
    if (i == 2) continue;
    cout << i << " ";
}

Nested Loops

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        cout << i << "," << j << " ";
    }
}

This produces coordinate pairs.

Infinite Loops

while (true) {
    // Loop forever unless break is used
}

Be cautious — always include an exit condition eventually.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic