While loop

From Seo Wiki - Search Engine Optimization and Programming Languages

Jump to: navigation, search

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement.

The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loops check the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.

For example, in the C programming language (as well as Java and C++, which use the same syntax in this case), the code fragment

x = 0;
while (x < 3)
{
   printf("x = %d\n",x);
   x++;
}

first checks whether x is less than 3, which it is, so it increments x by 1. It then checks the condition again, and executes again, repeating this process until the variable x has the value 3.

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.

Contents

Equivalent constructs

while (condition) {
   statements;
}

is equivalent to

if (condition) {
   do {
      statements;
   } while (condition);
}

or

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

or

   goto TEST;
LOOPSTART:
   statements;
TEST:
   if (condition) goto LOOPSTART;

Also, in C and its descendants, a while loop is a for loop with no initialization or counting expressions, i.e.,

for ( ; condition; )
{
   statements;
}

Demonstrating while loops

These while loops will calculate the factorial of the number 5:

Ada

Personal tools

Served in 0.295 secs.