While loop
![]()
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. OverviewA while consists of a block of code and a conditional expression.[1] The conditional is evaluated, and if true,[1] 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#,[2] Objective-C, and C++, (which use the same syntax in this case), the code fragment int x = 0;
while (x < 5) {
printf ("x = %d\n", x);
x++;
}
first checks whether x is less than 5, which it is, so the loop body is entered, where 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: while (true) {
// do complicated stuff
if (someCondition)
break;
// more stuff
}
ExamplesThese while loops calculate the factorial of 5: ActionScript 3var counter: int = 5;
var factorial: int = 1;
while (counter > 1) {
factorial *= counter;
counter--;
}
Printf("Factorial = %d", factorial);
AdaThe Wikibook Ada_Programming has a page on the topic of: Control 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;
APLcounter ← 5
factorial ← 1
:While counter > 0
factorial ×← counter
counter -← 1
:EndWhile
⎕ ← factorial
or simply !5
AutoHotkeycounter := 5
factorial := 1
While counter > 0
factorial *= counter--
MsgBox % factorial
Small Basiccounter = 5 ' Counter = 5
factorial = 1 ' initial value of variable "factorial"
While counter > 0
factorial = factorial * counter
counter = counter - 1
TextWindow.WriteLine(counter)
EndWhile
Visual BasicDim counter As Integer = 5 ' init variable and set value
Dim factorial As Integer = 1 ' initialize factorial variable
Do While counter > 0
factorial = factorial * counter
counter = counter - 1
Loop ' program goes here, until counter = 0
'Debug.Print factorial ' Console.WriteLine(factorial) in Visual Basic .NET
Bourne (Unix) shellcounter=5
factorial=1
while [ $counter -gt 0 ]; do
factorial=$((factorial * counter))
counter=$((counter - 1))
done
echo $factorial
C, C++int main() {
int count = 5;
int factorial = 1;
while (count > 1) {
factorial *= count--;
}
printf("%d", factorial);
}
ColdFusion Markup Language (CFML)Script syntaxcounter = 5;
factorial = 1;
while (counter > 1) {
factorial *= counter--;
}
writeOutput(factorial);
Tag syntax<cfset counter = 5>
<cfset factorial = 1>
<cfloop condition="counter GT 1">
<cfset factorial *= counter-->
</cfloop>
<cfoutput>#factorial#</cfoutput>
Fortranprogram FactorialProg
integer :: counter = 5
integer :: factorial = 1
do while (counter > 0)
factorial = factorial * counter
counter = counter - 1
end do
print *, factorial
end program FactorialProg
GoGo has no while statement, but it has the function of a for statement when omitting some elements of the for statement. counter, factorial := 5, 1
for counter > 1 {
counter, factorial = counter-1, factorial*counter
}
Java, C#, DThe code for the loop is the same for Java, C# and D: int counter = 5;
int factorial = 1;
while (counter > 1) {
factorial *= counter--;
}
JavaScriptlet counter = 5;
let factorial = 1;
while (counter > 1)
factorial *= counter--;
console.log(factorial);
Luacounter = 5
factorial = 1
while counter > 0 do
factorial = factorial * counter
counter = counter - 1
end
print(factorial)
MATLAB, Octavecounter = 5;
factorial = 1;
while (counter > 0)
factorial = factorial * counter; %Multiply
counter = counter - 1; %Decrement
end
factorial
MathematicaBlock[{counter=5,factorial=1}, (*localize counter and factorial*)
While[counter>0, (*While loop*)
factorial*=counter; (*Multiply*)
counter--; (*Decrement*)
];
factorial
]
Oberon, Oberon-2, Oberon-07, Component PascalMODULE 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.
Maya Embedded Languageint $counter = 5;
int $factorial = 1;
int $multiplication;
while ($counter > 0) {
$multiplication = $factorial * $counter;
$counter -= 1;
print("Counter is: " + $counter + ", multiplication is: " + $multiplication + "\n");
}
Nimvar
counter = 5 # Set counter value to 5
factorial = 1 # Set factorial value to 1
while counter > 0: # 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
Non-terminating while loop: while true:
echo "Help! I'm stuck in a loop!"
PascalPascal has two forms of the while loop, program Factorial1;
var
Fv: integer;
procedure fact(counter:integer);
var
Factorial: integer;
begin
Factorial := 1;
while Counter > 0 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.
Perlmy $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 open IN, "<test.txt";
while (<IN>) {
print;
}
close IN;
PHP$counter = 5;
$factorial = 1;
while ($counter > 0) {
$factorial *= $counter--; // Multiply, then decrement.
}
echo $factorial;
PL/IThe PL/I declare counter fixed initial(5);
declare factorial fixed initial(1);
do while(counter > 0)
factorial = factorial * counter;
counter = counter - 1;
end;
Pythoncounter = 5 # Set the value to 5
factorial = 1 # Set the value to 1
while counter > 0: # 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.
Non-terminating while loop: while True:
print("Help! I'm stuck in a loop!")
RacketIn 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)
However, an imperative programming style is often discouraged in Scheme and Racket. Ruby# Calculate the factorial of 5
i = 1
factorial = 1
while i <= 5
factorial *= i
i += 1
end
puts factorial
Rustfn main() {
let mut counter = 5;
let mut factorial = 1;
while counter > 1 {
factorial *= counter;
counter -= 1;
}
println!("{}", factorial);
}
SmalltalkContrary to other languages, in Smalltalk a while loop is not a language construct but defined in the class 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
Swiftvar counter = 5 // Set the initial counter value to 5
var factorial = 1 // Set the initial factorial value to 1
while counter > 0 { // 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.
Tclset counter 5
set factorial 1
while {$counter > 0} {
set factorial [expr $factorial * $counter]
incr counter -1
}
puts $factorial
VEXint counter = 5;
int factorial = 1;
while (counter > 1)
factorial *= counter--;
printf("%d", factorial);
PowerShell$counter = 5
$factorial = 1
while ($counter) {
$factorial *= $counter--
}
$factorial
While (language)While[3] is a simple programming language constructed from assignments, sequential composition, conditionals, and while statements, used in the theoretical analysis of imperative programming language semantics.[4][5] C := 5;
F := 1;
while (C > 1) do
F := F * C;
C := C - 1;
See also
References
|