World Library  
Flag as Inappropriate
Email this Article
 

Do while loop

Do While loop flow diagram

In most computer programming languages, a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block. Note though that unlike most languages, Fortran's do loop is actually the same as the for loop.

The do while construct consists of a process symbol and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Contrast with the while loop, which tests the condition before the code within the block is executed, the do-while loop is an exit-condition loop. This means that the code must always be executed first and then the expression or test condition is evaluated. If it is true, the code executes the body of the loop again. This process is repeated as long as the expression evaluates to true. If the expression is false, the loop terminates and control transfers to the statement following the do-while loop.

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 allows termination of the loop.

Some languages may use a different naming convention for this type of loop. For example, the Pascal language has a "repeat until" loop, which continues to run until the control expression is true (and then terminates) — whereas a "while" loop runs while the control expression is true (and terminates once the expression becomes false).

Contents

  • Equivalent constructs 1
  • Demonstrating do while loops 2
    • ActionScript 3 2.1
    • Ada 2.2
    • BASIC 2.3
    • C# 2.4
    • C 2.5
    • C++ 2.6
    • CFScript 2.7
    • D 2.8
    • Fortran 2.9
    • Java 2.10
    • JavaScript 2.11
    • PHP 2.12
    • PL/I 2.13
    • Python 2.14
    • Racket 2.15
    • Ruby 2.16
    • Smalltalk 2.17
    • Swift 2.18
    • Visual Basic .NET 2.19
  • See also 3
  • References 4

Equivalent constructs

do {
   do_work();  
} while (condition);

is equivalent to

do_work();
while (condition) {
   do_work();
}

In this manner, the do ... while loop saves the initial "loop priming" with do_work(); on the line before the while loop.

As long as the continue statement is not used, the above is technically equivalent to the following (though these examples are not typical or modern style):

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

or

LOOPSTART:
   do_work();
   if (condition) goto LOOPSTART;

Demonstrating do while loops

These example programs calculate the factorial of 5 using their respective languages' syntax for a do-while loop.

ActionScript 3

var counter:int = 5;
var factorial:int = 1;
do {
  factorial *= counter--; /* Multiply, then decrement. */
} while (counter > 0);
trace(factorial);

Ada

with Ada.Integer_Text_IO;

procedure Factorial is
  Counter   : Integer := 5;
  Factorial : Integer := 1;
begin
  loop
    Factorial := Factorial * Counter;
    Counter   := Counter - 1;
    exit when Counter = 0;
  end loop;

  Ada.Integer_Text_IO.Put (Factorial);
end Factorial;

BASIC

Early BASICs (such as GW-BASIC) used the syntax WHILE/WEND. Modern BASICs such as PowerBASIC provide both WHILE/WEND and DO/LOOP structures, with syntax such as DO WHILE/LOOP, DO UNTIL/LOOP, DO/LOOP WHILE, DO/LOOP UNTIL, and DO/LOOP (without outer testing, but with a conditional EXIT LOOP somewhere inside the loop). Typical BASIC source code:

Dim factorial As Integer
Dim counter As Integer
factorial = 1
counter = 5
Do 
   factorial = factorial * counter
   counter = counter - 1
Loop While counter > 0

C#

int counter = 5;
int factorial = 1;
do 
{
  factorial *= counter--; /* Multiply, then decrement. */
} while (counter > 0);
System.Console.WriteLine(factorial);

C

int counter = 5;
int factorial = 1;
do {
  factorial *= counter--; /* Multiply, then decrement. */
} while (counter > 0);
printf("factorial of 5 is %d\n", factorial);

C++

int counter = 5;
int factorial = 1;
do {
  factorial *= counter--;
} while (counter > 0);
std::cout<<"factorial of 5 is "<
    

[1]

CFScript

factorial = 1;
count = 10;
do {
   factorial *= count--;
} while (count > 1);

writeOutput(factorial);

D

int counter = 5;
int factorial = 1;

do {
  factorial *= counter--; // Multiply, then decrement.
} while (counter > 0);
writeln("factorial of 5 is ", factorial);

Fortran

With legacy FORTRAN 77 there is no DO-WHILE construct but the same effect can be achieved with GOTO:

      INTEGER CNT,FACT
      CNT=5
      FACT=1
    1 CONTINUE
      FACT=FACT*CNT
      CNT=CNT-1
      IF (CNT.GT.0) GOTO 1
      PRINT*,FACT
      END

With Fortran 90 and later, we use the equivalent construct mentioned above.

program FactorialProg
  integer :: counter = 5
  integer :: factorial = 1
  factorial = factorial * counter
  counter = counter - 1
  do while (counter > 0)
    factorial = factorial * counter
    counter = counter - 1
  end do
  print *, factorial
end program FactorialProg

Java

int counter = 5;
int factorial = 1;
do {
  factorial *= counter--; /* Multiply, then decrement. */
} while (counter > 0);
System.out.println(factorial);

JavaScript

var counter = 5;
var factorial = 1;
do {
    factorial *= counter--;
} while (counter > 0);
console.log(factorial);

[2]

PHP

 0);
echo $factorial;
?>

[3]

PL/I

The PL/I DO statement subsumes the functions of the post-test loop (do until), the pre-test loop (do while), and the for loop. All functions can be included in a single statement. The example shows only the "do until" syntax.

declare counter   fixed initial(5);
declare factorial fixed initial(1);
do until(counter<=0);
  factorial = factorial * counter;
  counter = counter - 1;
  end;
put(factorial);

Python

Python lacks a specific do while flow control construct. However, the equivalent may be constructed out of a while loop with a break.

counter = 5
factorial = 1
while True:
    factorial *= counter
    counter -= 1
    if counter == 0:
        break
print(factorial)

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 ()
  (set! factorial (* factorial counter))
  (set! counter (sub1 counter))
  (when (> counter 0) (loop)))
(displayln factorial)

Compare this with the first example of the while loop example for Racket.

Ruby

counter = 5
factorial = 1
begin
  factorial *= counter
  counter -= 1
end while counter > 0
puts factorial

Smalltalk

| counter factorial |
counter := 5.
factorial := 1.
[counter > 0] whileTrue: 
  [factorial := factorial * counter.
  counter := counter - 1].
Transcript show: factorial printString

Swift

Swift 2.x:

var counter = 5
var factorial = 1
repeat {
     factorial *= counter
     counter -= 1
} while counter > 0
print(factorial)

Swift 1.x:

var counter = 5
var factorial = 1
do {
     factorial *= counter
     counter -= 1
} while counter > 0
println(factorial)

Visual Basic .NET

Dim counter As Integer = 5
Dim factorial As Integer = 1
Do
   factorial *= counter
   counter -= 1 
Loop While counter > 0
Console.WriteLine(factorial)

See also

References

  1. ^ "C++ Do While Loop". 
  2. ^ "Mozilla Developer Network Documentation - The Do While Loop in JavaScript". 
  3. ^ "Do While - Official PHP Documentation". 
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.