The following types are written in C++, but apply to multiple languages.
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.
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.
A simplified way to create a while loop.2
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:
Could be written as the following for 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:
The following is a C-style While loop. It continues looping while x does not equal 3, or in other words it only stops looping when x equals 3. However, since x is initialized to 0 and the value of x is never changed in the loop, the loop will never end (infinite loop).
The while loop below will execute the code in the loop 5 times. x is initialized to 0, and each time in the loop the value of x is incremented. The while loop is set up to stop when x is equal to 5.
Conditional loops are often the source of an Off by one error.
"while loop - cppreference.com". en.cppreference.com. Retrieved 2023-11-07. https://en.cppreference.com/w/cpp/language/while ↩
"for loop - cppreference.com". en.cppreference.com. Retrieved 2023-11-07. https://en.cppreference.com/w/cpp/language/for ↩