World Library  
Flag as Inappropriate
Email this Article
 

While loop

While loop flow diagram

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.

Contents

  • Overview 1
  • Equivalent constructs 2
  • Demonstrating while loops 3
    • ActionScript 3 3.1
    • Ada 3.2
    • Basic - QBasic or Visual Basic 3.3
    • Bourne (Unix) shell 3.4
    • C or C++ 3.5
      • Script syntax 3.5.1
      • Tag syntax 3.5.2
    • Fortran 3.6
    • Java, C#, D 3.7
    • JavaScript 3.8
    • Lua 3.9
    • MATLAB 3.10
    • Mathematica 3.11
    • Oberon, Oberon-2, Oberon-07, or Component Pascal 3.12
    • Maya Embedded Language 3.13
    • Pascal 3.14
    • Perl 3.15
    • PHP 3.16
    • PL/I 3.17
    • Python 3.18
    • Racket 3.19
    • Ruby 3.20
    • Smalltalk 3.21
    • Tcl (Tool command language) 3.22
    • Windows PowerShell 3.23
    • While programming language 3.24
  • See also 4
  • References 5

Overview

The while construct consists of a block of code and a condition/expression.[1][2] The condition/expression is evaluated, and if the condition/expression is true, the code within 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 (as well as Java, C#,[3] 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 then the {loop body} 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 statement) that controls termination of the loop. For example:

while (true) 
{
    //do complicated stuff
    if (someCondition) break;
    //more stuff
}

Equivalent constructs

In the C programming language,

while (condition) 
{
   statements;
}

is equivalent to

if (condition) 
{
   do 
   {
      statements;
   } while (condition);
}

or

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

or

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

or

TEST:
   if (!condition) goto LOOPEND;
   statements
   goto TEST;
LOOPEND:

Those last two are not recommended because the use of "goto" statements makes it hard for a programmer to understand the flow of control, and is generally regarded as a last resort.

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:

ActionScript 3

var counter:int = 5;
var factorial:int = 1;

while ( counter > 1 )
{
  factorial *= counter;
  counter--;
}
trace ("Factorial ", factorial);

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

Basic - QBasic or Visual Basic

Dim counter As Integer = 10    ' init variable and set value

Do While counter > 0
    counter = counter - 1
Loop     ' program goes here, until counter = 0

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 (void)
{
  int counter = 5;
  long factorial = 1;
 
  while (counter > 1)
  {
     factorial *= counter--;
  }
  printf("%d", factorial);
  return 0;
}

Script syntax

counter = 5;
factorial = 1;
 
while ( counter > 1 ){
    factorial *= counter--;
}
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

Java, C#, D

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

int counter = 5;
long factorial = 1;

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

And finally in D

writefln(factorial);

JavaScript

var counter = 5;
var factorial = 1;

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

document.write(factorial);

Lua

counter = 5
factorial = 1

while counter > 0 do
  factorial = factorial * counter
  counter = counter - 1
end

print(factorial)

MATLAB

counter = 5;
factorial = 1;

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

factorial

Mathematica

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

Oberon, Oberon-2, 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)
{
    $multiplication = ($factorial * $counter);
     
    $counter -= 1;
    
    print ("Counter is: " + $counter + ", multiplication is: " + $multiplication + "\n");
}

Pascal

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

Perl

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:

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

PHP

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

PL/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 
                                      # factorial x counter.
    
    counter -= 1                      # Set the new value of 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 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

# Calculate the factorial of 5
i = 1
factorial = 1
while i < 5
  factorial *= i
  i += 1
end
puts 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.

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

Tcl (Tool command language)

set counter 5
set factorial 1

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

puts $factorial

Windows PowerShell

$number = 5
$counter = $number
$factorial = 1
while ($counter) {
    $factorial *= $counter--
}
$factorial

While programming language

The while programming language [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

References

  1. ^ http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
  2. ^ https://www.tutorialcup.com/cplusplus/while-loop.htm
  3. ^ "while (C# reference)". 
  4. ^ http://profs.sci.univr.it/~merro/files/WhileExtra_l.pdf
  5. ^ Flemming Nielson; Hanne R. Nielson; Chris Hankin (1999). Principles of Program Analysis. Springer.  
  6. ^ Illingworth, Valerie (11 December 1997). Dictionary of Computing. Oxford Paperback Reference (4th ed.). Oxford University Press.  
This article was sourced from Creative Commons Attribution-ShareAlike License; additional terms may apply. World Heritage Encyclopedia content is assembled from numerous content providers, Open Access Publishing, and in compliance with The Fair Access to Science and Technology Research Act (FASTR), Wikimedia Foundation, Inc., Public Library of Science, The Encyclopedia of Life, Open Book Publishers (OBP), PubMed, U.S. National Library of Medicine, National Center for Biotechnology Information, U.S. National Library of Medicine, National Institutes of Health (NIH), U.S. Department of Health & Human Services, and USA.gov, which sources content from all federal, state, local, tribal, and territorial government publication portals (.gov, .mil, .edu). Funding for USA.gov and content contributors is made possible from the U.S. Congress, E-Government Act of 2002.
 
Crowd sourced content that is contributed to World Heritage Encyclopedia is peer reviewed and edited by our editorial staff to ensure quality scholarly research articles.
 
By using this site, you agree to the Terms of Use and Privacy Policy. World Heritage Encyclopedia™ is a registered trademark of the World Public Library Association, a non-profit organization.
 



Copyright © World Library Foundation. All rights reserved. eBooks from Hawaii eBook Library are sponsored by the World Library Foundation,
a 501c(4) Member's Support Non-Profit Organization, and is NOT affiliated with any governmental agency or department.