Loops

Loops#

for loops#

We already saw how to loop over the elements of a vector:

for (auto e : vec) {
    // work on e
}

Now we’ll look at another type of for loop. This takes the form:

for (initializer ; condition ; iterator) {
     // do stuff
}

For example, to iterate from i = 0 to i = 9, we could do:

for (int i = 0; i < 10; ++i) {
    // work with i
}

We can use this to index a vector as well. For example:

Listing 49 vector_loop_manual.cpp#
#include <format>
#include <iostream>
#include <vector>

int main() {

    std::vector<int> vec{1, 2, 4, 8, 16, 32, 64, 128};

    for (std::size_t i = 0; i < vec.size(); ++i) {
        std::cout << std::format("element {} is {}\n", i, vec[i]);
    }

}

Tip

The behavior of the prefix and postfix operator is essentially the same when it is on its own line. Also in the for construction:

for (int i = 0; i < 10; ++i) {
    ...

it doesn’t matter much which version you use—although you will commonly see the prefix version used since it does not make a copy, and therefore can be faster.

Note

Just like with if, there is a single-statement form of for that doesn’t use brackets for the loop body—this should be avoided.

while loops#

The other type of loop in C++ is a while loops. This takes the form:

while (condition) {
    // do stuff
}

where the body is executed so long as condition is true. For example:

int i{1};

while (i < 10) {
   i = 2*i;
}

The loop body is only ever executed if the condition is true.

Warning

If we did int i{}, then this loop would be infinite, since i will always be 0.

To break out of a program that encountered an infinite loop, use Ctrl-c.

Caution

There is another form of the while loop that has the form:

do {
    // do stuff
} while (condition);

In this case, all of the statements in the loop body are executed at least once.

The do {} while (condition) form is discouraged.