Loops#

for loops#

We’ve already seen the basic structure of a for loop:

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

We can do this for just a simple integer counter:

for (int i = 0; i < 10; i += 2) {
     // we'll see i = 0, 2, 4, 6, 8
}

or with an iterator, like:

std::string my_string{"this is my string"};

for (auto it = my_string.begin(); it < my_string.end(); ++it) {
     // work on the string character by character
}

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.

We also saw the range-for loop that works with a variety of containers. For example:

std::vector<double> x{0.0, 1.0, 2.0, 3.0};

for (auto e : x) {
    // work on the current element in x
}

while and do-while loops#

There are two types of while loops in C++. The first takes the form:

while (condition) {
    // do stuff
}

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

int i{0};

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

The loop body is only ever executed if the condition is true. The other form puts the while at the end:

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

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

Note

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

Finally, you can loop over a range simply by using an initialization list:

Listing 35 list_loop.cpp#
#include <iostream>

int main() {

    for (auto year : {2020, 2021, 2022, 2023}) {
        std::cout << "the year is " << year << std::endl;
    }

}

continue and break#

Sometimes we want to exit a loop early or skip the remainder of the loop block if some conditions is met. This is where continue and break come into play.

It is not uncommon to write an infinite loop, like:

for (;;) {
    // do stuff
}

or

while (true) {
    // do stuff
}

In this case, we will want a way to bail out. Here’s an (silly) example of asking for a word from a user and telling them how many letters it contains. But if they enter “0”, we exit:

Listing 36 infinite_loop.cpp#
#include <iostream>
#include <string>

int main() {

    std::string word{};

    while (true) {

        std::cout << "Enter a word (0 to exit): ";
        std::cin >> word;

        if (word == "0") {
            break;
        }

        std::cout << word << " has " << word.size() << " characters" << std::endl;
    }

}

continue is used to skip to the next iteration. Here’s an example that loops over elements of a vector but only operates on them if they are even numbers, in which case, it negates them.

Listing 37 continue_example.cpp#
#include <iostream>
#include <vector>

int main() {

    std::vector<int> a{0, 4, 10, 3, 21, 100, 63, 7, 2, 1, 9, 20};

    for (auto &e : a) {
        if (e % 2 == 1) {
            continue;
        }
        e *= -1;
    }

    for (auto e : a) {
        std::cout << e << " ";
    }
    std::cout << std::endl;
}