- While loop
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 first evaluated - if the condition is true the code within the block is then 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 thedo 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 fragmentfirst 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.Equivalent constructs
is equivalent to
or
Also, in C and its descendants, a while loop is a for loop with no initialization or counting expressions, i.e.,
Demonstrating while loops
These while loops will calculate the
factorial of the number 5:
= Ada =QBasic orVisual Basic Visual Basic .NET
=C orC++ =The code for the loop is the same for Java and C#:
For Java the result is printed as follows:
The same in C#
JavaScript Matlab Mathematica Block [{counter=5,factorial=1}, (*localize counter and factorial*) While [counter>0, (*While loop*) factorial*=counter; (*Multiply*) counter--; (*Decrement*) ] ; factorial ]
Pascal
Perl Very similar to C and C++, but the "while loop" could also have been written on one line:
While loops are frequently used for reading data line by line (as defined by the
$/
line separator) from open filehandles:PHP
= Python =Smalltalk Contrary to other languages, in Smalltalk a while loop is not a language construct but defined in the class
BlockClosure
as a method with one parameter, the body as aclosure , using self as the condition.Tcl (Tool command language)Windows PowerShell $counter = 5 $factorial = 1 while ($counter -gt 0) { $factorial *= $counter-- # Multiply, then decrement. } Write-Output $factorial
See also
*
Do while loop
*For loop
*Foreach
Wikimedia Foundation. 2010.