Do while loop

From Vero - Wikipedia
Revision as of 07:04, 13 November 2025 by imported>Wws (Fortran: Version with test at the bottom)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Template:Short description {{SAFESUBST:#invoke:Unsubst||date=__DATE__ |$B= {{#switch: |Category=For categories, please use the templates available at Wikipedia:Categories for discussion. |Template=For templates, please use the templates available at Wikipedia:Templates for discussion. }}Template:Mbox{{#switch: |User|User talk= |#default={{#if:||Template:DMC}} }}Template:Merge partner }}

File:Do-while-loop-diagram.svg
Do While loop flow diagram

Template:Loop constructs

In computer programming, a do-while loop is a control flow statement that executes a block of code and then either repeats the block or exits the loop depending on a Boolean condition.

The do-while construct consists of a process symbol and a condition. First the code within the block is executed. 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.

Do-while loops check the condition after the block of code is executed. This control structure can be known as a post-test loop. This means the do-while loop is an exit-condition loop. However a while loop will test the condition before the code within the block is executed.

This means that the code is always executed first and then the expression or test condition is evaluated. This process is repeated as long as the expression evaluates to true. If the expression is false the loop terminates. A while loop sets the truth of a statement as a necessary condition for the code's execution. A do-while loop provides for the action's ongoing execution until the condition is no longer true.

It is possible and sometimes desirable for the condition to always evaluate to be true. This creates an infinite loop. When an infinite loop is created intentionally there is usually another control structure that allows termination of the loop. For example, a break statement would allow termination of an infinite loop.

Some languages may use a different naming convention for this type of loop. For example, the Pascal and Lua languages have a "repeat until" loop, which continues to run until the control expression is true and then terminates. In contrast a "while" loop runs while the control expression is true and terminates once the expression becomes false.

Equivalent constructs

<syntaxhighlight lang="c"> do {

   do_work();

} while (condition); </syntaxhighlight>

is equivalent to

<syntaxhighlight lang="c"> do_work();

while (condition) {

   do_work();

} </syntaxhighlight>

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 used in everyday computers):

<syntaxhighlight lang="c"> while (true) {

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

} </syntaxhighlight>

or

<syntaxhighlight lang="c"> LOOPSTART:

   do_work();
   if (condition) goto LOOPSTART;

</syntaxhighlight>

Examples

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

Ada

Template:Further <syntaxhighlight lang="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; </syntaxhighlight>

BASIC

Template:Further 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:

<syntaxhighlight lang="vbnet"> Dim factorial As Integer Dim counter As Integer

factorial = 1 counter = 5

Do

   factorial = factorial * counter
   counter = counter - 1

Loop While counter > 0

Print factorial </syntaxhighlight>

C, C++, D

Template:Further

The following function finds the first multiple of 7 greater than a given number. <syntaxhighlight lang="c++"> int first_multiple_of_7(int n) {

   do {
       n += 1;
   } while (n % 7 != 0);
   
   return n;

} </syntaxhighlight>

Examples <syntaxhighlight lang="c++"> printf("%d\n", first_multiple_of_7(10)); // 14 printf("%d\n", first_multiple_of_7(20)); // 21 printf("%d\n", first_multiple_of_7(28)); // 35 </syntaxhighlight>

Do-while(0) statements are also commonly used in C macros as a way to wrap multiple statements into a regular (as opposed to compound) statement. It makes a semicolon needed after the macro, providing a more function-like appearance for simple parsers and programmers as well as avoiding the scoping problem with <syntaxhighlight lang="text" class="" style="" inline="1">if</syntaxhighlight>. It is recommended in CERT C Coding Standard rule PRE10-C.<ref>Template:Cite web</ref>

Fortran

Template:Further With legacy Fortran 77 there is no DO-WHILE construct but the same effect can be achieved with GOTO: <syntaxhighlight lang="fortran">

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

</syntaxhighlight>

Fortran 90 and later supports a DO-While construct, however the test is at the top of the loop. To write a loop with the test at the bottom, an infinite DO construct is used, with an IF-EXIT sequence at the end:

<syntaxhighlight lang="fortran"> program FactorialProg

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

end program FactorialProg </syntaxhighlight>

Java

Template:Further <syntaxhighlight lang="java"> int counter = 5; int factorial = 1;

do {

   factorial *= counter--; // Multiply, then decrement.

} while (counter > 0);

System.out.printf("The factorial of 5 is %d%n", factorial); </syntaxhighlight>

Kotlin

Template:Main Source:<ref>Template:Cite web</ref> <syntaxhighlight lang="kotlin"> var counter = 5 var factorial = 1

do {

   factorial = factorial * counter
   counter = counter - 1

} while (counter > 1)

println(factorial) </syntaxhighlight>


Pascal

Template:Further Pascal uses repeat/until syntax instead of do-while.

<syntaxhighlight lang="pascal"> factorial := 1; counter := 5; repeat

  factorial := factorial * counter;
  counter := counter - 1; // In Object Pascal one may use dec (counter);

until counter = 0; </syntaxhighlight>

PL/I

Template:Further 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.

<syntaxhighlight lang="rexx"> declare counter fixed initial(5); declare factorial fixed initial(1);

do until(counter <= 0);

   factorial = factorial * counter;
   counter = counter - 1;

end;

put(factorial); </syntaxhighlight>

Python

Python does not have a DO-WHILE loop, but its effect can be achieved by an infinite loop with a breaking condition at the end.

The following function finds the first multiple of 7 greater than a given number. <syntaxhighlight lang="python"> def first_multiple_of_7(n):

   while True:
       n += 1
       if n % 7 == 0:
           break
   return n

</syntaxhighlight>

Examples <syntaxhighlight lang="python"> print(first_multiple_of_7(10)) # 14 print(first_multiple_of_7(20)) # 21 print(first_multiple_of_7(28)) # 35 </syntaxhighlight>

Racket

Template:Further In Racket, as in other Scheme implementations, a "named-let" is a popular way to implement loops:

<syntaxhighlight lang="racket">

  1. lang racket

(define counter 5) (define factorial 1) (let loop ()

   (set! factorial (* factorial counter))
   (set! counter (sub1 counter))
   (when (> counter 0) (loop)))

(displayln factorial) </syntaxhighlight>

Compare this with the first example of the while loop example for Racket. Be aware that a named let can also take arguments.

Racket and Scheme also provide a proper do loop. <syntaxhighlight lang="scheme"> (define (factorial n)

   (do ((counter n (- counter 1))
       (result 1 (* result counter)))
   ((= counter 0) result) ; Stop condition and return value.
   ; The body of the do-loop is empty.
   ))

</syntaxhighlight>

Smalltalk

Template:Further <syntaxhighlight lang="smalltalk"> | counter factorial | counter := 5. factorial := 1.

[counter > 0] whileTrue:

   [factorial := factorial * counter.
   counter := counter - 1].

Transcript show: factorial printString </syntaxhighlight>

See also

References

Template:Reflist

Template:Wikibooks

de:Schleife (Programmierung)#Do-While-Schleife