Do while loop

Do while loop
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, Fortran's do loop is actually analogous to the for loop.

The do while construct consists of a block of code 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.

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

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

is equivalent to

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

which (as long as the continue statement is not used) 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;

Bash

#! /bin/bash
counter=5
factorial=1
while [ $counter -gt 0 ]; do
   factorial=$(($factorial*$counter))
   counter=$(($counter-1))
done
echo $factorial

Note: Bash only does integer mathematics. For real numbers, try piping output through awk or bc.

C or C++

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

A do while loop may be employed in macros since they shouldn't provide the final semicolon (;).[1] Thus a multi-statement macro such as swap where the first parameter is the type can be executed only once using a do while loop where the condition is 0:

#define SWAP(type, x, y) do{type tmp=x; x=y; y=tmp;} while(0)

C#

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

Fortran

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

With Fortran 90 and later, the following is also valid. Using it is better practice, since it is immediately apparent that this is a while-loop.

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

public class Factorial{
  public static void main(String[] args){
    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--; /* Multiply, then decrement. */
} while (counter > 0);
document.body.appendChild(document.createTextNode(factorial));
}

Perl

$counter = 5;
$factorial = 1;
do {
     $factorial *= $counter--;
} while ($counter > 0);
print $factorial;

PHP

<?php
$counter = 5;
$factorial = 1;
do {
     $factorial *= $counter--;
} while ($counter > 0);
echo $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

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. ^ Question 10.4 Q: What's the best way to write a multi-statement macro?

Wikimedia Foundation. 2010.

Игры ⚽ Нужен реферат?

Look at other dictionaries:

  • 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… …   Wikipedia

  • 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 — 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”