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 evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loop checks 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 < 5) {
printf ("x = %d\n", x);
x++;
}
first checks whether x is less than 5, which it is, so then the {loop body} is entered, where the printf function is run and x is incremented by 1. After completing all the statements in the loop body, the condition, (x < 5), is checked again, and the loop is executed again, this process repeating until the variable x has the value 5.
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:
while (true) {
//do complicated stuff
if (someCondition)
break;
//more stuff
}
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;
or
TEST:
if (!condition) goto LOOPEND;
statements
goto TEST;
LOOPEND:
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:
var i:int = 1;
while ( i < 6)
{
trace ("Number ", i);
i = i*i;
}
with Ada.Integer_Text_IO;
procedure Factorial is
Counter : Integer := 5;
Factorial : Integer := 1;
begin
while Counter > 0 loop
Factorial := Factorial * Counter;
Counter := Counter - 1;
end loop;
Ada.Integer_Text_IO.Put (Factorial);
end Factorial;
counter=5
factorial=1
while [ $counter -gt 0 ]; do
factorial=$((factorial * counter))
counter=$((counter - 1))
done
echo $factorial
Dim counter As Integer = 10 ' init variable and set value
Do While counter > 0
counter = counter - 1
Loop ' program goes here, until counter = 0
unsigned int counter = 5;
unsigned long factorial = 1;
while (counter > 0)
{
factorial *= counter--; /* Multiply and decrement */
}
printf("%lu", factorial);
program FactorialProg
integer :: counter = 5
integer :: factorial = 1
do while (counter > 0)
factorial = factorial * counter
counter = counter - 1
end do
print *, factorial
end program FactorialProg
The code for the loop is the same for Java, C# and D:
int counter = 5;
long factorial = 1;
while (counter > 1)
{
factorial *= counter--;
}
For Java the result is printed as follows:
System.out.println(factorial);
The same in C#
System.Console.WriteLine(factorial);
And finally in D
writefln(factorial);
var counter = 5;
var factorial = 1;
while ( counter > 1 )
{
factorial *= counter--;
}
document.write(factorial);
counter = 5
factorial = 1
while counter > 0 do
factorial = factorial * counter
counter = counter - 1
end
print(factorial)
counter = 5;
factorial = 1;
while (counter > 0)
factorial = factorial * counter; %Multiply
counter = counter - 1; %Decrement
end
factorial
Block[{counter=5,factorial=1}, (*localize counter and factorial*) While[counter>0, (*While loop*) factorial*=counter; (*Multiply*) counter--; (*Decrement*) ]; factorial ]
MODULE Factorial;
IMPORT Out;
VAR
Counter, Factorial: INTEGER;
BEGIN
Counter := 5;
Factorial := 1;
WHILE Counter > 0 DO
Factorial := Factorial * Counter;
DEC(Counter)
END;
Out.Int(Factorial,0)
END Factorial.
program Factorial1;
var
Counter, Factorial: integer;
begin
Counter := 5;
Factorial := 1;
while Counter > 0 do
begin
Factorial := Factorial * Counter;
Counter := Counter - 1
end;
WriteLn(Factorial)
end.
my $counter = 5;
my $factorial = 1;
while ( $counter > 0 ) {
$factorial *= $counter--; # Multiply, then decrement
}
print $factorial;
While loops are frequently used for reading data line by line (as defined by the $/
line separator) from open filehandles:
open IN, "<test.txt";
while ( <IN> ) {
print;
}
close IN;
$counter = 5;
$factorial = 1;
while($counter > 0) {
$factorial *= $counter; // Multiply first.
$counter--; // then decrement.
}
print $factorial;
counter = 5 # Set the value to 5
factorial = 1 # Set the value to 1
while counter > 0: # While counter(5) is greater than 0
factorial = factorial * counter # Set new value of factorial to
# factorial x counter.
counter = counter - 1 # Set the new value of counter to
# counter - 1.
print factorial # Print the value of factorial.
Non Terminating While Loop:-
while 1 == 1:
print "Help! I am Lost in this Loop."
In Racket, as in other Scheme implementations, a "named-let" is a popular way to implement loops:
#lang racket
(define counter 5)
(define factorial 1)
(let loop ()
(when (> counter 0)
(set! factorial (* factorial counter))
(set! counter (sub1 counter))
(loop)))
(displayln factorial)
Using a macro system, implementing a while-loop is a trivial exercise (commonly used to introduce macros):
#lang racket
(define-syntax-rule (while test body ...) ; implements a while loop
(let loop () (when test body ...) (loop)))
(define counter 5)
(define factorial 1)
(while (> counter 0)
(set! factorial (* factorial counter))
(set! counter (sub1 counter)))
(displayln factorial)
But note that an imperative programming style is often discouraged in Racket (as in Scheme).
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 a closure, using self as the condition.
Smalltalk also has a corresponding whileFalse: method.
| count factorial |
count := 5.
factorial := 1.
[ count > 0 ] whileTrue:
[ factorial := factorial * count
count := count - 1 ]
Transcript show: factorial
Tcl (Tool command language)
set counter 5
set factorial 1
while {$counter > 0} {
set factorial [expr $factorial * $counter]
incr counter -1
}
puts $factorial
$counter = 5 $factorial = 1 while ($counter -gt 0) { $factorial *= $counter-- # Multiply, then decrement. } Write-Output $factorial