Jump to content

Do while loop: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Python: deleted python example as python does not have a do while construct.
removed unnecessary examples
Line 54: Line 54:
{{disputed section|The example is both wrong and fails to teach a lesson|date=November 2020}}
{{disputed section|The example is both wrong and fails to teach a lesson|date=November 2020}}
These example programs calculate the [[factorial]] of 5 using their respective languages' syntax for a do-while loop.
These example programs calculate the [[factorial]] of 5 using their respective languages' syntax for a do-while loop.

===[[ActionScript|ActionScript 3]]===
<syntaxhighlight lang="actionscript">
var counter: int = 5;
var factorial: int = 1;

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

trace(factorial);
</syntaxhighlight>


===[[Ada (programming language)|Ada]]===
===[[Ada (programming language)|Ada]]===
Line 104: Line 92:
</syntaxhighlight>
</syntaxhighlight>


===[[C Sharp (programming language)|C#]]===
===[[C (programming language)|C]]/[[C++]]===
<syntaxhighlight lang="csharp">
int counter = 5;
int factorial = 1;

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

System.Console.WriteLine(factorial);
</syntaxhighlight>

===[[C (programming language)|C]]===
<syntaxhighlight lang="c">
<syntaxhighlight lang="c">
int counter = 5;
int counter = 5;
Line 130: Line 105:


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 {{code|if}}. It is recommended in [[CERT C Coding Standard]] rule PRE10-C.<ref>{{cite web |title=C multi-line macro: do/while(0) vs scope block |url=https://stackoverflow.com/a/1067238 |website=Stack Overflow}}</ref>
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 {{code|if}}. It is recommended in [[CERT C Coding Standard]] rule PRE10-C.<ref>{{cite web |title=C multi-line macro: do/while(0) vs scope block |url=https://stackoverflow.com/a/1067238 |website=Stack Overflow}}</ref>

===[[C++]]===
<syntaxhighlight lang="cpp">
int counter = 5;
int factorial = 1;

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

std::cout << "factorial of 5 is "<< factorial << std::endl;
</syntaxhighlight>

===[[CFScript]]===
<syntaxhighlight lang="javascript">
factorial = 1;
count = 10;

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

writeOutput(factorial);
</syntaxhighlight>


===[[D (programming language)|D]]===
===[[D (programming language)|D]]===
Line 211: Line 162:


System.out.println("The factorial of 5 is " + factorial);
System.out.println("The factorial of 5 is " + factorial);

//============================================//
// The below function does the same as above. //
//============================================//

int counter = 5;
int factorial = 1;

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

System.out.println("The factorial of 5 is " + factorial);
</syntaxhighlight>

===[[JavaScript]]===
<syntaxhighlight lang="javascript">
let counter = 5; // Declaring two variables, counter and factorial
let factorial = 1;

do {
factorial *= counter--; //What will be looped
} while (counter > 0); //The looping conditions

console.log(factorial); //Showing the result
</syntaxhighlight>
<ref>{{Cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while|title=do...while|website=MDN Web Docs}}</ref>

===[[Kotlin (programming language)|Kotlin]]===
<syntaxhighlight lang="kotlin">
var counter = 5
var factorial = 1
//These line of code is almost the same as the above JavaScript codes, the only difference is the keyword that shows the results
do {
factorial *= counter--
} while (counter > 0)

println("Factorial of 5 is $factorial")
</syntaxhighlight>
</syntaxhighlight>
<ref>{{Cite web|url=https://kotlinlang.org/docs/reference/control-flow.html|title=Control Flow: if, when, for, while - Kotlin Programming Language|website=Kotlin}}</ref>


===[[Pascal (programming language)|Pascal]]===
===[[Pascal (programming language)|Pascal]]===


[[Pascal (programming language)|Pascal]] does not have a do/while; instead, it has a repeat/until. As mentioned in the introduction, one can consider a repeat/until to be equivalent to a 'do code while not expression' construct.
[[Pascal (programming language)|Pascal]] does uses repeat/until syntax instead of do while.


<syntaxhighlight lang="pascal">
<syntaxhighlight lang="pascal">
Line 263: Line 175:
counter := counter - 1; // In Object Pascal one may use dec (counter);
counter := counter - 1; // In Object Pascal one may use dec (counter);
until counter = 0;
until counter = 0;
</syntaxhighlight>

===[[PHP]]===
<syntaxhighlight lang="php">
$counter = 5;
$factorial = 1;

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

echo $factorial;
</syntaxhighlight>
</syntaxhighlight>


Line 316: Line 216:
; The body of the do-loop is empty.
; The body of the do-loop is empty.
))
))
</syntaxhighlight>

===[[Ruby (programming language)|Ruby]]===
<syntaxhighlight lang="ruby">
counter = 10
factorial = 2

begin
factorial *= counter
counter -= 2
end while counter > 1

puts factorial
</syntaxhighlight>
</syntaxhighlight>


Line 343: Line 230:
Transcript show: factorial printString
Transcript show: factorial printString
</syntaxhighlight>
</syntaxhighlight>

===[[Swift (programming language)|Swift]]===
Swift 2.x and later:<ref>{{Cite web|url=https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID126|title=Control Flow — The Swift Programming Language (Swift 5.3)|website=docs.swift.org}}</ref>
<syntaxhighlight lang="swift">
var counter = 5
var factorial = 1

repeat {
factorial *= counter
counter -= 1
} while counter > 0

print(factorial)
</syntaxhighlight>
Swift 1.x:
<syntaxhighlight lang="swift">
var counter = 5
var factorial = 1

do {
factorial *= counter
counter -= 1
} while counter > 0

println(factorial)
</syntaxhighlight>

===[[Visual Basic .NET]]===
<syntaxhighlight lang="vbnet">
Dim counter As Integer = 5
Dim factorial As Integer = 1

Do
factorial *= counter
counter -= 1
Loop While counter > 0

Console.WriteLine(factorial)</syntaxhighlight>


==See also==
==See also==

Revision as of 20:05, 19 November 2023

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 and then either repeats the block or exits the loop depending on a given 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

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

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.

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;

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

Print factorial
int counter = 5;
int factorial = 1;

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

printf("factorial of 5 is %d\n", factorial);

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 if. It is recommended in CERT C Coding Standard rule PRE10-C.[1]

int counter = 5;
int factorial = 1;

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

writeln("factorial of 5 is ", factorial);

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

Fortran 90 and later does not have a do-while construct either, but it does have a while loop construct which uses the keywords "do while" and is thus actually the same as the for loop.[2]

program FactorialProg
    integer :: counter = 5
    integer :: factorial = 1
    
    factorial = factorial * counter
    counter = counter - 1
    
    do while (counter > 0) ! Truth value is tested before the loop
        factorial = factorial * counter
        counter = counter - 1
    end do
    
    print *, factorial
end program FactorialProg
int counter = 5;
int factorial = 1;

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

System.out.println("The factorial of 5 is " + factorial);

Pascal does uses repeat/until syntax instead of do while.

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

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

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. Be aware that a named let can also take arguments.

Racket and Scheme also provide a proper do loop.

(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.
    ))
| counter factorial |
counter := 5.
factorial := 1.

[counter > 0] whileTrue: 
    [factorial := factorial * counter.
    counter := counter - 1].

Transcript show: factorial printString

See also

References

  1. ^ "C multi-line macro: do/while(0) vs scope block". Stack Overflow.
  2. ^ "Microsoft visual basic". msdn.microsoft.com. Retrieved 21 January 2016.