While loop
Template:Short description Template:Use dmy dates {{SAFESUBST:#invoke:Unsubst||date=__DATE__ |$B= {{#switch: |Category=For categories, please use the templates available at Wikipedia:Categories for discussion. |Template=For templates, please use the templates available at Wikipedia:Templates for discussion. }}Template:Mbox{{#switch: |User|User talk= |#default={{#if:||Template:DMC}} }}Template:Merge partner }} Template:Refimprove
In computer programming, a while loop is a control flow statement that allows code to be executed repeatedly based on a Boolean condition. The while loop can be thought of as a repeating if statement.
Overview
A while consists of a block of code and a conditional expression.<ref name=":0">Template:Cite web</ref> The conditional is evaluated, and if true,<ref name=":0" /> the block of code is executed. This repeats until the conditional becomes false. Because the while loop checks the conditional before the block is executed, the control structure is also known as a pre-test loop. In contrast, do-while loop tests the conditional after the block.
For example, in the languages C, Java, C#,<ref>Template:Cite web</ref> Objective-C, and C++, (which use the same syntax in this case), the code fragment
<syntaxhighlight lang="c"> int x = 0; while (x < 5) {
printf ("x = %d\n", x);
x++;
} </syntaxhighlight>
first checks whether x is less than 5, which it is, so the loop body is entered, where Template:Code is called and x is incremented by 1. After completing the statements in the loop body, the condition, (x < 5), is checked again, and the loop is executed again. This process repeats until x has the value 5.
The condition can always valuate as true to create an infinite loop. In this case, there may be a early-exit control structure (such as a break statement) that controls termination of the loop. For example:
<syntaxhighlight lang="c"> while (true) {
// do complicated stuff
if (someCondition)
break;
// more stuff
} </syntaxhighlight>
Examples
These while loops calculate the factorial of 5:
ActionScript 3
Template:Further <syntaxhighlight lang="actionscript"> var counter: int = 5; var factorial: int = 1;
while (counter > 1) {
factorial *= counter; counter--;
}
Printf("Factorial = %d", factorial); </syntaxhighlight>
Ada
Template:Further Template:Wikibooks <syntaxhighlight lang="ada"> with Ada.Integer_Text_IO;
procedure Factorial is
Counter : Integer := 5; Factorial : Integer := 1;
begin
while Counter > 1 loop
Factorial := Factorial * Counter;
Counter := Counter - 1;
end loop;
Ada.Integer_Text_IO.Put (Factorial);
end Factorial; </syntaxhighlight>
APL
Template:Further <syntaxhighlight lang="apl"> counter ← 5 factorial ← 1
- While counter > 1
factorial ×← counter counter -← 1
- EndWhile
⎕ ← factorial </syntaxhighlight>
or simply <syntaxhighlight lang="apl"> !5 </syntaxhighlight>
AutoHotkey
Template:Further <syntaxhighlight lang="autohotkey"> counter := 5 factorial := 1
While counter > 1
factorial *= counter--
MsgBox % factorial </syntaxhighlight>
Small Basic
Template:Further <syntaxhighlight lang="vbnet"> counter = 5 ' Counter = 5 factorial = 1 ' initial value of variable "factorial"
While counter > 1
factorial = factorial * counter counter = counter - 1
EndWhile
TextWindow.WriteLine("Factorial = " + factorial) </syntaxhighlight>
Visual Basic
Template:Further <syntaxhighlight lang="vbnet"> Dim counter As Integer = 5 ' init variable and set value Dim factorial As Integer = 1 ' initialize factorial variable
Do While counter > 1
factorial = factorial * counter counter = counter - 1
Loop ' program goes here, until counter = 0
'Debug.Print factorial ' Console.WriteLine(factorial) in Visual Basic .NET </syntaxhighlight>
Bourne (Unix) shell
Template:Further <syntaxhighlight lang="bash"> counter=5 factorial=1 while [ $counter -gt 1 ]; do
factorial=$((factorial * counter)) counter=$((counter - 1))
done
echo $factorial </syntaxhighlight>
C, C++
Template:Further <syntaxhighlight lang="c"> int main() {
int counter = 5; int factorial = 1;
while (counter > 1) {
factorial *= counter--;
}
printf("%d", factorial);
} </syntaxhighlight>
ColdFusion Markup Language (CFML)
Script syntax
<syntaxhighlight lang="cfs"> counter = 5; factorial = 1;
while (counter > 1) {
factorial *= counter--;
}
writeOutput(factorial); </syntaxhighlight>
Tag syntax
Template:Further <syntaxhighlight lang=CFM> <cfset counter = 5> <cfset factorial = 1> <cfloop condition="counter GT 1">
<cfset factorial *= counter-->
</cfloop> <cfoutput>#factorial#</cfoutput> </syntaxhighlight>
Fortran
Template:Further <syntaxhighlight lang="fortran"> program FactorialProg
integer :: counter = 5 integer :: factorial = 1
do while (counter > 1)
factorial = factorial * counter
counter = counter - 1
end do
print *, factorial
end program FactorialProg </syntaxhighlight>
Go
Template:Further Go has no while statement, but it has the function of a for statement when omitting some elements of the for statement.
<syntaxhighlight lang="go"> counter, factorial := 5, 1
for counter > 1 { counter, factorial = counter-1, factorial*counter } </syntaxhighlight>
Java, C#, D
Template:Further The code for the loop is the same for Java, C# and D:
<syntaxhighlight lang="csharp"> int counter = 5; int factorial = 1;
while (counter > 1) {
factorial *= counter--;
} </syntaxhighlight>
JavaScript
Template:Further <syntaxhighlight lang="javascript"> let counter = 5; let factorial = 1;
while (counter > 1)
factorial *= counter--;
console.log(factorial); </syntaxhighlight>
Kotlin
Template:Main Source:<ref>Template:Cite web</ref> <syntaxhighlight lang="kotlin"> var counter = 5 var factorial = 1
while (counter > 1) {
factorial = factorial * counter counter = counter - 1
}
println(factorial) </syntaxhighlight>
Lua
Template:Further <syntaxhighlight lang="lua"> counter = 5 factorial = 1
while counter > 1 do
factorial = factorial * counter counter = counter - 1
end
print(factorial) </syntaxhighlight>
MATLAB, Octave
Template:Further <syntaxhighlight lang="matlab"> counter = 5; factorial = 1;
while (counter > 0)
factorial = factorial * counter; %Multiply counter = counter - 1; %Decrement
end
factorial </syntaxhighlight>
Mathematica
Template:Further <syntaxhighlight lang="mathematica"> Block[{counter=5,factorial=1}, (*localize counter and factorial*)
While[counter>1, (*While loop*)
factorial*=counter; (*Multiply*)
counter--; (*Decrement*)
];
factorial
] </syntaxhighlight>
Oberon, Oberon-2, Oberon-07, Component Pascal
Template:Further <syntaxhighlight lang="cp"> MODULE Factorial; IMPORT Out; VAR
Counter, Factorial: INTEGER;
BEGIN
Counter := 5; Factorial := 1;
WHILE Counter > 1 DO
Factorial := Factorial * Counter;
DEC(Counter)
END;
Out.Int(Factorial,0)
END Factorial. </syntaxhighlight>
Maya Embedded Language
Template:Further <syntaxhighlight lang="perl"> int $counter = 5; int $factorial = 1;
while ($counter > 1) {
$factorial *= $counter; $counter -= 1;
}
print("Factorial = " + $factorial + "\n"); </syntaxhighlight>
Nim
Template:Further <syntaxhighlight lang="nim"> var
counter = 5 # Set counter value to 5 factorial = 1 # Set factorial value to 1
while counter > 1: # While counter is greater than 0
factorial *= counter # Set new value of factorial to counter. dec counter # Set the counter to counter - 1.
echo factorial </syntaxhighlight>
Non-terminating while loop:
<syntaxhighlight lang="nim"> while true:
echo "Help! I'm stuck in a loop!"
</syntaxhighlight>
Pascal
Template:Further Pascal has two forms of the while loop, Template:Code and Template:Code. Template:Code repeats one statement (unless enclosed in a begin-end block) as long as the condition is true. Template:Code repetitively executes a block of one or more statements until the a condition is false. The main difference between the two is that Template:Code executes zero times if the condition is initially false, whereas Template:Code executes at least once.
<syntaxhighlight lang="pascal"> program Factorial1; var
Fv: integer;
procedure fact(counter:integer);
var
Factorial: integer;
begin
Factorial := 1;
while Counter > 1 do
begin
Factorial := Factorial * Counter;
Counter := Counter - 1
end;
WriteLn(Factorial)
end;
begin
Write('Enter a number to return its factorial: ');
readln(fv);
repeat
fact(fv);
Write('Enter another number to return its factorial (or 0 to quit): ');
until fv=0;
end. </syntaxhighlight>
Perl
Template:Further <syntaxhighlight lang="perl"> my $counter = 5; my $factorial = 1;
while ($counter > 1) {
$factorial *= $counter--; # Multiply, then decrement
}
print $factorial; </syntaxhighlight>
While loops are frequently used for reading data line by line (as defined by the $/ line separator) from open filehandles:
<syntaxhighlight lang="perl"> open IN, "<test.txt";
while (<IN>) {
print;
}
close IN; </syntaxhighlight>
PHP
Template:Further <syntaxhighlight lang="php"> $counter = 5; $factorial = 1;
while ($counter > 1) {
$factorial *= $counter--; // Multiply, then decrement.
}
echo $factorial; </syntaxhighlight>
PL/I
Template:Further
The PL/I DO statement can act as either a for loop, a while loop, or a do until loop.
<syntaxhighlight lang="rexx">
declare counter fixed initial(5);
declare factorial fixed initial(1);
do while(counter > 1)
factorial = factorial * counter; counter = counter - 1;
end; </syntaxhighlight>
Python
Template:Further <syntaxhighlight lang="python"> counter = 5 # Set the value to 5 factorial = 1 # Set the value to 1
while counter > 1: # While counter(5) is greater than 0
factorial *= counter # Set new value of factorial to counter. counter -= 1 # Set the counter to counter - 1.
print(factorial) # Print the value of factorial. </syntaxhighlight>
Non-terminating while loop:
<syntaxhighlight lang="python"> while True:
print("Help! I'm stuck in a loop!")
</syntaxhighlight>
Racket
Template:Further In Racket, as in other Scheme implementations, a named-let is a popular way to implement loops: <syntaxhighlight lang="racket">
- lang racket
(define counter 5) (define factorial 1) (let loop ()
(when (> counter 1)
(set! factorial (* factorial counter))
(set! counter (sub1 counter))
(loop)))
(displayln factorial) </syntaxhighlight> Using a macro system, implementing a while loop is a trivial exercise (commonly used to introduce macros): <syntaxhighlight lang="racket">
- 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 1)
(set! factorial (* factorial counter)) (set! counter (sub1 counter)))
(displayln factorial) </syntaxhighlight> However, an imperative programming style is often discouraged in Scheme and Racket.
Ruby
<syntaxhighlight lang="ruby">
- Count Down Variant
counter = 5 factorial = 1
while counter > 1
factorial *= counter counter -= 1
end
puts factorial </syntaxhighlight>
<syntaxhighlight lang="ruby">
- Count Up Variant
counter = 2 factorial = 1
while counter <= 5
factorial *= counter counter += 1
end
puts factorial </syntaxhighlight>
Rust
Template:Further <syntaxhighlight lang="rust"> fn main() {
let mut counter = 5; let mut factorial = 1;
while counter > 1 {
factorial *= counter;
counter -= 1;
}
println!("{}", factorial);
} </syntaxhighlight>
Smalltalk
Template:Further
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.
<syntaxhighlight lang="smalltalk"> | count factorial | count := 5. factorial := 1. [count > 0] whileTrue:
[factorial := factorial * count. count := count - 1].
Transcript show: factorial </syntaxhighlight>
Swift
Template:Further <syntaxhighlight lang="swift"> var counter = 5 // Set the initial counter value to 5 var factorial = 1 // Set the initial factorial value to 1
while counter > 1 { // While counter(5) is greater than 0
factorial *= counter // Set new value of factorial to factorial x counter. counter -= 1 // Set the new value of counter to counter - 1.
}
print(factorial) // Print the value of factorial. </syntaxhighlight>
Tcl
Template:Further <syntaxhighlight lang="tcl"> set counter 5 set factorial 1
while {$counter > 1} {
set factorial [expr $factorial * $counter] incr counter -1
}
puts $factorial </syntaxhighlight>
PowerShell
Template:Further <syntaxhighlight lang="powershell"> $counter = 5 $factorial = 1
while ($counter) {
$factorial *= $counter--
}
$factorial </syntaxhighlight>
While (language)
While<ref>Template:Cite web</ref> is a simple programming language constructed from assignments, sequential composition, conditionals, and while statements, used in the theoretical analysis of imperative programming language semantics.<ref name="NielsonNielson1999">Template:Cite book</ref><ref>Template:Cite book</ref> <syntaxhighlight lang="whiley"> C := 5; F := 1;
while (C > 1) do
F := F * C; C := C - 1;
</syntaxhighlight>
See also
- Do while loop
- For loop
- Foreach
- Primitive recursive function
- General recursive function
- LOOP (programming language) – a programming language with the property that the functions it can compute are exactly the primitive recursive functions
References
- Pages with templates in the wrong namespace
- Pages with broken file links
- Control flow
- Iteration in programming
- Programming language comparisons
- Articles with example Ada code
- Articles with example BASIC code
- Articles with example C code
- Articles with example C++ code
- Articles with example C Sharp code
- Articles with example D code
- Articles with example Fortran code
- Articles with example Java code
- Articles with example JavaScript code
- Articles with example MATLAB/Octave code
- Articles with example Pascal code
- Articles with example Perl code
- Articles with example PHP code
- Articles with example Python (programming language) code
- Articles with example Racket code
- Articles with example Ruby code
- Articles with example Rust code
- Articles with example Smalltalk code
- Articles with example Swift code
- Articles with example Tcl code