Do while loop
|
In most computer programming languages, a do while loop is a control structure that allows code to be executed repeatedly based on a given Boolean condition.
The do while construct consists of a block of code and a condition. The code within the block is first executed, then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Compare with the while loop, which tests the condition before the code within the block has executed.
Note that it is possible, and in some cases desirable, for the condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (such as a break statement) that controls termination of the loop.
For example, in the C programming language, the code fragment
x = 0; do { x = x + 1; } while (x < 3);
first it executes the instruction x = x + 1, then checks the condition x < 3, which it is not, so it executes again. It repeats this execute and check process until the variable x has the desired value, 3.
Contents |
Demonstrating do while loops
These do while loops will calculate the factorial of a number:
QBasic or Visual Basic
Dim counter As Integer : counter = 5 Dim factorial as Long : factorial = 1 Do factorial = factorial * counter 'multiply counter = counter - 1 'decrement While (counter > 0) Print factorial
C or C++
unsigned int counter = 5; unsigned long factorial = 1; do { factorial *= counter--; /*Multiply, then decrement.*/ } while (counter > 0); printf("%i", factorial);
Java
int counter = 5; long factorial = 1; do { factorial *= counter--; //Multiply, then decrement. } while (counter > 0); System.out.println(factorial);