![]() | It has been suggested that Do while loop be merged into this article. ( Discuss ) Proposed since September 2025. |
This article needs additional citations for verification .(October 2016) |
Loop constructs |
---|
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.
A 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
intx=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 printf()
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:
while(true){// do complicated stuffif(someCondition)break;// more stuff}
These while loops calculate the factorial of 5:
varcounter:int=5;varfactorial:int=1;while(counter>1){factorial*=counter;counter--;}Printf("Factorial = %d",factorial);
withAda.Integer_Text_IO;procedureFactorialisCounter:Integer:=5;Factorial:Integer:=1;beginwhileCounter>0loopFactorial:=Factorial*Counter;Counter:=Counter-1;endloop;Ada.Integer_Text_IO.Put(Factorial);endFactorial;
counter←5factorial←1:Whilecounter>0factorial×←countercounter-←1:EndWhile⎕←factorial
or simply
!5
counter:=5factorial:=1Whilecounter>0factorial*=counter--MsgBox%factorial
counter=5' Counter = 5factorial=1' initial value of variable "factorial"Whilecounter>0factorial=factorial*countercounter=counter-1TextWindow.WriteLine(counter)EndWhile
DimcounterAsInteger=5' init variable and set valueDimfactorialAsInteger=1' initialize factorial variableDoWhilecounter>0factorial=factorial*countercounter=counter-1Loop' program goes here, until counter = 0'Debug.Print factorial ' Console.WriteLine(factorial) in Visual Basic .NET
counter=5factorial=1while[$counter-gt0];dofactorial=$((factorial*counter))counter=$((counter-1))doneecho$factorial
intmain(){intcount=5;intfactorial=1;while(count>1){factorial*=count--;}printf("%d",factorial);}
counter=5;factorial=1;while(counter>1){factorial*=counter--;}writeOutput(factorial);
<cfsetcounter=5><cfsetfactorial=1><cfloopcondition="counter GT 1"><cfsetfactorial*=counter--></cfloop><cfoutput>#factorial#</cfoutput>
program FactorialProginteger::counter=5integer::factorial=1do while(counter>0)factorial=factorial*countercounter=counter-1end do print*,factorialend program FactorialProg
Go has no while statement, but it has the function of a for statement when omitting some elements of the for statement.
counter,factorial:=5,1forcounter>1{counter,factorial=counter-1,factorial*counter}
The code for the loop is the same for Java, C# and D:
intcounter=5;intfactorial=1;while(counter>1){factorial*=counter--;}
letcounter=5;letfactorial=1;while(counter>1)factorial*=counter--;console.log(factorial);
counter=5factorial=1whilecounter>0dofactorial=factorial*countercounter=counter-1endprint(factorial)
counter=5;factorial=1;while(counter>0)factorial=factorial*counter;%Multiplycounter=counter-1;%Decrementendfactorial
Block[{counter=5,factorial=1},(*localize counter and factorial*)While[counter>0,(*While loop*)factorial*=counter;(*Multiply*)counter--;(*Decrement*)];factorial]
MODULEFactorial;IMPORTOut;VARCounter,Factorial:INTEGER;BEGINCounter:=5;Factorial:=1;WHILECounter>0DOFactorial:=Factorial*Counter;DEC(Counter)END;Out.Int(Factorial,0)ENDFactorial.
int$counter=5;int$factorial=1;int$multiplication;while($counter>0){$multiplication=$factorial*$counter;$counter-=1;print("Counter is: "+$counter+", multiplication is: "+$multiplication+"\n");}
varcounter=5# Set counter value to 5factorial=1# Set factorial value to 1whilecounter>0:# While counter is greater than 0factorial*=counter# Set new value of factorial to counter.deccounter# Set the counter to counter - 1.echofactorial
Non-terminating while loop:
whiletrue:echo"Help! I'm stuck in a loop!"
Pascal has two forms of the while loop, while
and repeat-until
. while
repeats one statement (unless enclosed in a begin-end block) as long as the condition is true. repeat-until
repetitively executes a block of one or more statements until the a condition is false. The main difference between the two is that while
executes zero times if the condition is initially false, whereas repeat-until
executes at least once.
programFactorial1;varFv:integer;procedurefact(counter:integer);varFactorial:integer;beginFactorial:=1;whileCounter>0dobeginFactorial:=Factorial*Counter;Counter:=Counter-1end;WriteLn(Factorial)end;beginWrite('Enter a number to return its factorial: ');readln(fv);repeatfact(fv);Write('Enter another number to return its factorial (or 0 to quit): ');untilfv=0;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:
openIN,"<test.txt";while(<IN>){print;}closeIN;
$counter=5;$factorial=1;while($counter>0){$factorial*=$counter--;// Multiply, then decrement.}echo$factorial;
The PL/I DO
statement can act as either a for loop, a while loop, or a do until loop.
declarecounterfixedinitial(5); declarefactorialfixedinitial(1);dowhile(counter>0)factorial=factorial*counter;counter=counter-1;end;
counter=5# Set the value to 5factorial=1# Set the value to 1whilecounter>0:# While counter(5) is greater than 0factorial*=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:
whileTrue:print("Help! I'm stuck in a loop!")
In Racket, as in other Scheme implementations, a named-let is a popular way to implement loops:
#lang racket(definecounter5)(definefactorial1)(letloop()(when(>counter0)(set!factorial(*factorialcounter))(set!counter(sub1counter))(loop)))(displaylnfactorial)
Using a macro system, implementing a while loop is a trivial exercise (commonly used to introduce macros):
#lang racket(define-syntax-rule(whiletestbody...); implements a while loop(letloop()(whentestbody...(loop))))(definecounter5)(definefactorial1)(while(>counter0)(set!factorial(*factorialcounter))(set!counter(sub1counter)))(displaylnfactorial)
However, an imperative programming style is often discouraged in Scheme and Racket.
# Calculate the factorial of 5i=1factorial=1whilei<=5factorial*=ii+=1endputsfactorial
fnmain(){letmutcounter=5;letmutfactorial=1;whilecounter>1{factorial*=counter;counter-=1;}println!("{}",factorial);}
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].Transcriptshow:factorial
varcounter=5// Set the initial counter value to 5varfactorial=1// Set the initial factorial value to 1whilecounter>0{// While counter(5) is greater than 0factorial*=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.
setcounter5setfactorial1while{$counter>0}{setfactorial[expr$factorial*$counter]incrcounter-1}puts$factorial
intcounter=5;intfactorial=1;while(counter>1)factorial*=counter--;printf("%d",factorial);
$counter=5$factorial=1while($counter){$factorial*=$counter--}$factorial
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)doF:=F*C;C:=C-1;