vimwiki

C++ loops

while

int count = 1;

while (count <= 5) {
    std::cout << count;
    count ++;
}

do-while

int price = 300;

do {
    std::cout << "Too expensive";
} while (price > 500);

for

for (int i = 1; i<=n; i++) {
    std::cout << i;
}

for-each

int my_list[5] = {0, 1, 2, 3, 4};

for (int number : my_list) {
    std::cout << number;
}

The counter variable can be declared with auto keyword.

C++ deduce the type based on the type of the list

int my_list[5] = {0, 1, 2, 3, 4};

for (auto number : my_list) {
    std::cout << number;
}

break and continue

break

The break keyword is used to jump out of a loop.

for (int i = 0; i < 10; i++) {
    if (i == 4) {
        break;
    }
    std::cout << i;
}

Difference between break and return

continue

Skip an iteration of a loop. If continue is executed, the loop skip the iteration and goes to the next.

for (int i = 0; i < 10; i++) {
    // 4 is not printed, but the rest is
    if (i == 4) {
        continue;
    }
    std::cout << i;