Tie koodariksi

C++ Programming

Chapter 5: Loops

For loop

The structure of the for loop is
for (start; condition; change) {
    code
}
At the beginning of the loop, the start command is executed, followed by a number of rounds. At the beginning of each round, the condition is checked. If the condition holds, then code is performed, and then the change command, after which the next round begins. If the condition does not apply, the loop ends.

A common use for the for loop is to iterate through:

for (int i = 1; i <= 10; i++) {
    cout << i << " ";
}
The code prints out the following:
1 2 3 4 5 6 7 8 9 10

While loop

The structure of a while loop is as follows:
while (condition) {
    code
}
At the beginning of each round of the loop, it is checked if condition applies, and if it does, the code inside the loop executes. The loop ends when the condition is no longer valid.

Here's how to use the while loop:

int a = 1, b = 10;
while (a < b) {
    cout << a << " " << b << " ";
    a++; b--;
}
The code prints the following:
1 10 2 9 3 8 4 7 5 6

Do loop

A rarer loop is the do loop, having the following structure:
do {
    code
} while (condition);
This works the same way as the while loop, but the condition is only checked at the end of the loop. Therefore, the code is executed at least once.

The following code describes how the do loop works:

int x = 100;
do {
    cout << x << " ";
    x /= 2;
} while (x != 0);
The code prints the following:
100 50 25 12 6 3 1

Break command

The break command interrupts the loop and moves on to the subsequent line.

For example, the following loop condition is true, which is would ensure it repeats forever. However, the break command interrupts the loop.

int x = 1;
while (true) {
    cout << x << " ";
    if (x == 10) break;
    x++;
}
The code returns the following result:
1 2 3 4 5 6 7 8 9 10

Continue command

The continue command goes directly to the next round of the loop and does not execute the remaining code in the current round.

For example, the following loop goes through the numbers 1...10, but the continue command moves to the next round if the number is even, so the loop only prints odd numbers.

for (int i = 1; i <= 10; i++) {
    if (i%2 == 0) continue;
    cout << i << " ";
}
The code returns the following result:
1 3 5 7 9

Goto command

Yet another way to influence program execution is the goto command, which jumps to the position of a specified label in the code. For example, in the following code, the goto command jumps to the end label, from which point execution continues.
goto end;
cout << "monkey\n";
cout << "banana\n";
end:
cout << "harpsichord\n";
In this case, the goto command means only the following line is printed:
harpsichord
However, you should usually use other techniques instead of goto because using it can quickly make code confusing.

Datatähti 2027 – peruskoulun ja lukion ohjelmointikilpailu käynnissä 26.10.–8.11.2026