While loop
Find sources: "While loop" – news · newspapers · books · scholar · JSTOR (October 2016) (Learn how and when to remove this message)
| 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.
Overview
[edit ]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 stuff if(someCondition) break; // more stuff }
Examples
[edit ]These while loops calculate the factorial of 5:
ActionScript 3
[edit ]varcounter:int=5; varfactorial:int=1; while(counter>1){ factorial*=counter; counter--; } Printf("Factorial = %d",factorial);
Ada
[edit ]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;
APL
[edit ]counter←5 factorial←1 :Whilecounter>1 factorial×ばつ←counter counter-←1 :EndWhile ⎕←factorial
or simply
!5
AutoHotkey
[edit ]counter := 5 factorial := 1 While counter > 1 factorial *= counter-- MsgBox % factorial
Small Basic
[edit ]counter=5' Counter = 5 factorial=1' initial value of variable "factorial" Whilecounter>1 factorial=factorial*counter counter=counter-1 EndWhile TextWindow.WriteLine("Factorial = "+factorial)
Visual Basic
[edit ]DimcounterAsInteger=5' init variable and set value DimfactorialAsInteger=1' initialize factorial variable DoWhilecounter>1 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) shell
[edit ]counter=5 factorial=1 while[$counter-gt1];do factorial=$((factorial*counter)) counter=$((counter-1)) done echo$factorial
C, C++
[edit ]intmain(){ intcounter=5; intfactorial=1; while(counter>1){ factorial*=counter--; } printf("%d",factorial); }
ColdFusion Markup Language (CFML)
[edit ]Script syntax
[edit ]counter = 5; factorial = 1; while (counter > 1) { factorial *= counter--; } writeOutput(factorial);
Tag syntax
[edit ]<cfset counter = 5> <cfset factorial = 1> <cfloop condition="counter GT 1"> <cfset factorial *= counter--> </cfloop> <cfoutput>#factorial#</cfoutput>
Fortran
[edit ]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
Go
[edit ]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,1 forcounter>1{ counter,factorial=counter-1,factorial*counter }
Java, C#, D
[edit ]The code for the loop is the same for Java, C# and D:
intcounter=5; intfactorial=1; while(counter>1){ factorial*=counter--; }
JavaScript
[edit ]letcounter=5; letfactorial=1; while(counter>1) factorial*=counter--; console.log(factorial);
Kotlin
[edit ]Source:[3]
varcounter=5 varfactorial=1 while(counter>1){ factorial=factorial*counter counter=counter-1 } println(factorial)
Lua
[edit ]counter=5 factorial=1 whilecounter>1do factorial=factorial*counter counter=counter-1 end print(factorial)
MATLAB, Octave
[edit ]counter=5; factorial=1; while(counter>0) factorial=factorial*counter;%Multiply counter=counter-1;%Decrement end factorial
Mathematica
[edit ]Block[{counter=5,factorial=1},(*localize counter and factorial*) While[counter>1,(*While loop*) factorial*=counter;(*Multiply*) counter--;(*Decrement*) ]; factorial ]
Oberon, Oberon-2, Oberon-07, Component Pascal
[edit ]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.
Maya Embedded Language
[edit ]int$counter=5; int$factorial=1; while($counter>1){ $factorial*=$counter; $counter-=1; } print("Factorial = "+$factorial+"\n");
Nim
[edit ]var counter=5# Set counter value to 5 factorial=1# Set factorial value to 1 whilecounter>1:# While counter is greater than 0 factorial*=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
[edit ]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; var Fv:integer; procedurefact(counter:integer); var Factorial:integer; begin Factorial:=1; whileCounter>1do 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): '); untilfv=0; end.
Perl
[edit ]my$counter=5; my$factorial=1; while($counter>1){ $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;
PHP
[edit ]$counter = 5; $factorial = 1; while ($counter > 1) { $factorial *= $counter--; // Multiply, then decrement. } echo $factorial;
PL/I
[edit ]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>1) factorial=factorial*counter; counter=counter-1; end;
Python
[edit ]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.
Non-terminating while loop:
while True: print("Help! I'm stuck in a loop!")
Racket
[edit ]In Racket, as in other Scheme implementations, a named-let is a popular way to implement loops:
#lang racket (definecounter5) (definefactorial1) (letloop() (when(>counter1) (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(>counter1) (set!factorial(*factorialcounter)) (set!counter(sub1counter))) (displaylnfactorial)
However, an imperative programming style is often discouraged in Scheme and Racket.
Ruby
[edit ]# Count Down Variant counter=5 factorial=1 whilecounter>1 factorial*=counter counter-=1 end putsfactorial
# Count Up Variant counter=2 factorial=1 whilecounter<=5 factorial*=counter counter+=1 end putsfactorial
Rust
[edit ]fnmain(){ letmutcounter=5; letmutfactorial=1; whilecounter>1{ factorial*=counter; counter-=1; } println!("{}",factorial); }
Smalltalk
[edit ]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
Swift
[edit ]varcounter=5// Set the initial counter value to 5 varfactorial=1// Set the initial factorial value to 1 whilecounter>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.
Tcl
[edit ]setcounter5 setfactorial1 while{$counter>1}{ setfactorial[expr$factorial*$counter] incrcounter-1 } puts$factorial
PowerShell
[edit ]$counter = 5 $factorial = 1 while ($counter) { $factorial *= $counter-- } $factorial
While (language)
[edit ]While[4] is a simple programming language constructed from assignments, sequential composition, conditionals, and while statements, used in the theoretical analysis of imperative programming language semantics.[5] [6]
C := 5; F := 1; while (C > 1) do F := F * C; C := C - 1;
See also
[edit ]- 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
[edit ]- ^ a b "The while and do-while Statements (The Java Tutorials > Learning the Java Language > Language Basics)". Dosc.oracle.com. Retrieved 21 October 2016.
- ^ "while (C# reference)". Msdn.microsoft.com. Retrieved 21 October 2016.
- ^ "Conditions and loops | Kotlin". Kotlin Help. Retrieved 21 October 2025.
- ^ "Chapter 3: The While programming language" (PDF). Profs.sci.univr.it. Retrieved 21 October 2016.
- ^ Flemming Nielson; Hanne R. Nielson; Chris Hankin (1999). Principles of Program Analysis. Springer. ISBN 978-3-540-65410-0 . Retrieved 29 May 2013.
- ^ Illingworth, Valerie (11 December 1997). Dictionary of Computing . Oxford Paperback Reference (4th ed.). Oxford University Press. ISBN 9780192800466.