While loop
   HOME

TheInfoList



OR:

In most computer programming languages, a while loop is a
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
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.


Overview

The ''while'' construct consists of a block of code and a condition/expression. The condition/expression is evaluated, and if the condition/expression is ''true'', the code within all of their following in the block is executed. This repeats until the condition/expression becomes false. Because the ''while'' loop checks the condition/expression before the block is executed, the control structure is often also known as a pre-test loop. Compare this with the ''do while'' loop, which tests the condition/expression ''after'' the loop has executed. For example, in the
C programming language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well a ...
(as well as
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, C#,
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXT ...
, and C++, which use the same syntax in this case), the code fragment int x = 0; while (x < 5) first checks whether x is less than 5, which it is, so then the 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 Break or Breaks or The Break may refer to: Time off from duties * Recess (break), time in which a group of people is temporarily dismissed from its duties * Break (work), time off during a shift/recess ** Coffee break, a short mid-morning rest ...
statement) that controls termination of the loop. For example: while (true)


Demonstrating ''while'' loops

These ''while'' loops will calculate the
factorial In mathematics, the factorial of a non-negative denoted is the product of all positive integers less than or equal The factorial also equals the product of n with the next smaller factorial: \begin n! &= n \times (n-1) \times (n-2) \ ...
of the number 5:


ActionScript 3 ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meaning ...

var counter: int = 5; var factorial: int = 1; while (counter > 1) Printf("Factorial = %d", factorial);


Ada Ada may refer to: Places Africa * Ada Foah, a town in Ghana * Ada (Ghana parliament constituency) * Ada, Osun, a town in Nigeria Asia * Ada, Urmia, a village in West Azerbaijan Province, Iran * Ada, Karaman, a village in Karaman Province, T ...

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;


APL

counter ← 5 factorial ← 1 :While counter > 0 factorial ×← counter counter -← 1 :EndWhile ⎕ ← factorial


AutoHotkey

counter := 5 factorial := 1 While counter > 0 factorial *= counter-- MsgBox % factorial


Microsoft Small Basic

counter = 5 ' Counter = 5 factorial = 1 ' initial value of variable "factorial" While counter > 0 factorial = factorial * counter counter = counter - 1 TextWindow.WriteLine(counter) EndWhile


Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to: * Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET * Visual Basic ( ...

Dim 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) shell

counter=5 factorial=1 while $counter -gt 0 do factorial=$((factorial * counter)) counter=$((counter - 1)) done echo $factorial


C or C++

int main()


CFML ColdFusion Markup Language, more commonly known as CFML, is a scripting language for web development that runs on the JVM, the .NET framework, and Google App Engine. Multiple commercial and open source implementations of CFML engines are availab ...


Script syntax

counter = 5; factorial = 1; while (counter > 1) writeOutput(factorial);


Tag syntax

#factorial#


Fortran

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


Go

Go does not have a while statement, but it has the function of a for statement if you omit some elements of the for statement. counter, factorial := 5, 1 for counter > 1


Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, C#, D

The code for the loop is the same for Java, C# and D: int counter = 5; int factorial = 1; while (counter > 1) factorial *= counter--;


JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...

let counter = 5; let factorial = 1; while (counter > 1) factorial *= counter--; console.log(factorial);


Lua

counter = 5 factorial = 1 while counter > 0 do factorial = factorial * counter counter = counter - 1 end print(factorial)


MATLAB MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementat ...
&
GNU Octave GNU Octave is a high-level programming language primarily intended for scientific computing and numerical computation. Octave helps in solving linear and nonlinear problems numerically, and for performing other numerical experiments using a lan ...

counter = 5; factorial = 1; while (counter > 0) factorial = factorial * counter; %Multiply counter = counter - 1; %Decrement end factorial


Mathematica Wolfram Mathematica is a software system with built-in libraries for several areas of technical computing that allow machine learning, statistics, symbolic computation, data manipulation, network analysis, time series analysis, NLP, optimiza ...

Block (*localize counter and factorial*) While[counter>0, (*While loop*) factorial*=counter; (*Multiply*) counter--; (*Decrement*) factorial ]


Oberon (programming language), Oberon, Oberon-2 (programming language), Oberon-07, or Component Pascal

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.


Maya Embedded Language

int $counter = 5; int $factorial = 1; int $multiplication; while ($counter > 0)


Nim

var 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!"


Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Frenc ...

Pascal has two forms of the while loop, while and repeat. While repeats one statement (unless enclosed in a begin-end block) as long as the condition is true. The repeat statement repetitively executes a block of one or more statements through an until statement and continues repeating unless the condition is false. The main difference between the two is the while loop may execute zero times if the condition is initially false, the repeat-until loop always executes at least once. 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.


Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...

my $counter = 5; my $factorial = 1; while ($counter > 0) print $factorial; ''While'' loops are frequently used for reading data line by line (as defined by the $/ line separator) from open filehandles: open IN, ") close IN;


PHP

$counter = 5; $factorial = 1; while ($counter > 0) echo $factorial;


PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...

declare counter fixed initial(5); declare factorial fixed initial(1); do while(counter > 0) factorial = factorial * counter; counter = counter - 1; end;


Python

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 *= 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

In Racket, as in other
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
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).


Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...

# Calculate the factorial of 5 i = 1 factorial = 1 while i <= 5 factorial *= i i += 1 end puts factorial


Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO( ...

fn main()


Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan ...

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. ount > 0whileTrue: actorial := factorial * count. count := count - 1 Transcript show: factorial


Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...

var counter = 5 // Set the initial counter value to 5 var factorial = 1 // Set the initial factorial value to 1 while counter > 0 print(factorial) // Print the value of factorial.


Tcl

set counter 5 set factorial 1 while puts $factorial


VEX

int counter = 5; int factorial = 1; while (counter > 1) factorial *= counter--; printf("%d", factorial);


PowerShell PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sou ...

$counter = 5 $factorial = 1 while ($counter) $factorial


While programming language

The While programming language is a simple programming language constructed from assignments, sequential composition, conditionals and while statements, used in the theoretical analysis of imperative programming language semantics. C := 5; F := 1; while (C > 1) do F := F * C; C := C - 1;


See also

* Do while loop *
For loop In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied. For-loops have two par ...
* Foreach *
LOOP (programming language) LOOP is a simple register language that precisely captures the primitive recursive functions. The language is derived from the counter-machine model. Like the counter machines the LOOP language comprises a set of one or more unbounded ''registers ...
– a programming language with the property that the functions it can compute are exactly the primitive recursive functions


References

{{DEFAULTSORT:While Loop Control flow Articles with example Ada code Articles with example C code Articles with example Fortran code Articles with example Pascal code Articles with example Perl code Articles with example Python (programming language) code Articles with example Racket code Articles with example Smalltalk code