wikiwand.com

Conditional loop - Wikiwand

The following types are written in C++, but apply to multiple languages.

While loop

Checks condition for truthfulness before executing any of the code in the loop.[1] If condition is initially false, the code inside the loop will never be executed. In PL/I this is a DO WHILE... statement.

while (condition) {
    // code
}

Do-While loop

Checks condition for truthfulness after executing the code in the loop. Therefore, the code inside the loop will always be executed at least once. PL/I implements this as a DO UNTIL... statement.

do {
    // code
} while (condition);

For loop

A simplified way to create a while loop.[2]

for (initialization; condition; statement) {
    // code
}

Initialization is executed just once before the loop. Condition evaluates the boolean expression of the loop. Statement is executed at the end of every loop.

So for example, the following while loop:

int i = 0;
while (i < 10) {
    // code
    
    i += 1;
}

Could be written as the following for loop:

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

For-Each loop

A for-each loop is essentially equivalent to an iterator. It allows a program to iterate through a data structure without having to keep track of an index. It is especially useful in Sets which do not have indices. An example is as follows:

std::vector<std::string> range = { "apple", "banana", "orange" };
for (auto item: range) {
    // code
}