While loop


While loop

In most computer programming languages, a while loop is a control flow 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.

The "while" construct consists of a block of code and a condition. The condition is first evaluated - if the condition is true the code within the block is then executed. This repeats until the condition becomes false. Because "while" loops check the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition "after" the loop has executed.

For example, in the C programming language (as well as Java and C++, which use the same syntax in this case), the code fragment

x = 0;while (x < 3){ printf("x = %d ",x); x++;}

first checks whether x is less than 3, which it is, so it increments x by 1. It then checks the condition again, and executes again, repeating this process until the variable x has the value 3.

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 statement) that controls termination of the loop.

Equivalent constructs

while (condition) { statements;}

is equivalent to

while (true) { if (!condition) break; statements;}

or

goto TEST;LOOPSTART: statements;TEST: if (condition) goto LOOPSTART;

Also, in C and its descendants, a while loop is a for loop with no initialization or counting expressions, i.e.,

for ( ; condition; ){ statements;}

Demonstrating while loops

These while loops will calculate the factorial of the number 5:


= Ada =

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 Main;

QBasic or Visual Basic

' Initialize the variablesDim counter As Integer : counter = 5Dim factorial As Long : factorial = 1

Do While counter > 0 factorial = factorial * counter ' Multiply counter = counter - 1 ' DecrementLoop

Print factorial ' Prints out the result.

Visual Basic .NET

' Initialize the variablesDim counter As UInteger = 5Dim factorial As UInteger = 1

Do While counter > 0 factorial *= counter ' Multiply counter -= 1 ' DecrementLoop

System.Console.WriteLine(factorial) ' Prints out the result.


=C or C++=

unsigned int counter = 5;unsigned long factorial = 1;

while (counter > 0){ factorial *= counter--; //Multiply and decrement}

printf("%i", factorial);

Java, C#

The code for the loop is the same for Java and C#:

int counter = 5;long factorial = counter;

while (--counter > 1){ factorial *= counter;}

For Java the result is printed as follows: System.out.println(factorial);

The same in C# System.Console.WriteLine(factorial);

JavaScript

var counter = 5;var factorial = counter;

while (--counter > 1){ factorial *= counter;}

document.body.appendChild(document.createTextNode(factorial));

Matlab

counter = 5;factorial = 1;

while (counter > 0) factorial = factorial * counter; %Multiply counter = counter - 1; %Decrementend

factorial

Mathematica

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

Pascal

program Factorial;var Counter, Factorial: integer;begin Counter := 5; Factorial := 1; while Counter > 0 do begin Factorial := Factorial * Counter; Counter := Counter - 1; end; Write(Factorial);end.

Perl

my $counter = 5;my $factorial = 1;

while ( $counter > 0 ) { $factorial *= $counter--; # Multiply, then decrement}

print $factorial;

Very similar to C and C++, but the "while loop" could also have been written on one line:

$factorial *= $counter-- while $counter > 0;

While loops are frequently used for reading data line by line (as defined by the $/ line separator) from open filehandles:

open IN, " ){ print;}close IN;

PHP

$counter = 5;$factorial = 1;while($counter > 0) { $factorial *= $counter--; // Multiply, then decrement.}echo $factorial;


= Python =

counter = 5factorial = 1while counter > 0: factorial *= counter counter -= 1print factorial

Smalltalk

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.


count factorial
count := 5.factorial := 1. [ count > 0 ] whileTrue: [ factorial := factorial * (count := count - 1) ] Transcript show: factorial

Tcl (Tool command language)

set counter 5set factorial 1

while {$counter > 0} { set factorial [expr $factorial * $counter] incr counter -1 }

puts $factorial

Windows PowerShell

$counter = 5 $factorial = 1 while ($counter -gt 0) { $factorial *= $counter-- # Multiply, then decrement. } Write-Output $factorial

See also

* Do while loop
* For loop
* Foreach


Wikimedia Foundation. 2010.

Look at other dictionaries:

  • while loop — noun A section of computer code in which an instruction or group of instructions is executed only while a certain condition continues to be met. :Example (from C++) …   Wiktionary

  • Do while loop — diagram In most computer programming languages, a do while loop, sometimes just called a do loop, is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Note though that unlike most languages,… …   Wikipedia

  • do while loop — loop in computers which exists as long as a certain condition is preserved …   English contemporary dictionary

  • Loop inversion — is a compiler optimization, a loop transformation, which replaces a while loop by an if block containing a do..while loop. Example in C int i, a [100] ; i = 0; while (i < 100) { a [i] = 0; i++; }is equivalent to: int i, a [100] ; i = 0; if (i <… …   Wikipedia

  • Loop variant — In computer science, a loop variant is a mathematical function defined on the state space of a computer program having the property that each iteration of a loop (given its invariant) strictly decreases its value with respect to a well founded… …   Wikipedia

  • Loop invariant — In computer science, a loop invariant is an invariant used to prove properties of loops.Specifically in Floyd Hoare logic, the partial correctness of a while loop is governed by the following rule of inference::frac{{Cland I};mathrm{body};{I… …   Wikipedia

  • Loop optimization — In compiler theory, loop optimization plays an important role in improving cache performance, making effective use of parallel processing capabilities, and reducing overheads associated with executing loops. Most execution time of a scientific… …   Wikipedia

  • LOOP-Programme — sind Programme in der Programmiersprache LOOP, einer stark eingeschränkten, modellhaften Sprache, die nur die Formulierung von Additionen, Wertzuweisungen und endlich oft durchlaufenen Schleifen erlaubt. LOOP Programme spielen in der… …   Deutsch Wikipedia

  • Loop-Berechenbarkeit — LOOP Programme sind Programme in der Programmiersprache LOOP, einer stark eingeschränkten, modellhaften Sprache, die nur die Formulierung von Additionen, Wertzuweisungen und endlich oft durchlaufenen Schleifen erlaubt. LOOP Programme spielen in… …   Deutsch Wikipedia

  • Loop-Programm — LOOP Programme sind Programme in der Programmiersprache LOOP, einer stark eingeschränkten, modellhaften Sprache, die nur die Formulierung von Additionen, Wertzuweisungen und endlich oft durchlaufenen Schleifen erlaubt. LOOP Programme spielen in… …   Deutsch Wikipedia


Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”

We are using cookies for the best presentation of our site. Continuing to use this site, you agree with this.