Do while loop

From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search

In most computer programming languages, a do while loop, sometimes just called a do loop, is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Note though that unlike most languages, Fortran's do loop is actually analogous to the for loop.

The do while construct consists of a block of code and a condition. First, the code within the block is executed, and 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. Contrast with the while loop, which tests the condition before the code within the block is executed.

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 allows termination of the loop.

Some languages may use a different naming convention for this type of loop. For example, the Pascal language has a "repeat until" loop, which continues to run until the control expression is true (and then terminates) — whereas a "do-while" loop runs while the control expression is true (and terminates once the expression becomes false).

Contents

Equivalent constructs

do {
   statements;
} while (condition);

is not equivalent to

statements;
while (condition) {
   statements;
}

but (as long as the continue statement is not used) is equivalent to

while (true) {
   statements;
   if (!condition) break;
}

or to

LOOPSTART:
   statements;
   if (condition) goto LOOPSTART;

Demonstrating do while loops

These example programs calculate the factorial of 5 using their respective languages' syntax for a do-while loop.


Ada

Personal tools

Served in 0.142 secs.