Loops/Do-while: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|NS-HUBASIC}}: NS-HUBASIC example added)
Line 1,699: Line 1,699:
val += 1
val += 1
echo val</lang>
echo val</lang>

=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 PRINT "NO,"A" ISN'T A MULTIPLE OF 6."
20 A=A+1
30 IF A-(A/6)*6<>0 THEN GOTO 10
40 PRINT "YES, 6 IS A MULTIPLE OF 6."</lang>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==

Revision as of 18:08, 12 November 2019

Task
Loops/Do-while
You are encouraged to solve this task according to the task description, using any language you may know.

Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once.


Related tasks


Reference



360 Assembly

Basic

The WTO macro is in SYS1.MACLIB, which needs to be in the SYSLIB concatenation at assembly. <lang 360asm>* Do-While DOWHILE CSECT , This program's control section

        BAKR  14,0               Caller's registers to linkage stack 
        LR    12,15              load entry point address into Reg 12 
       USING  DOWHILE,12         tell assembler we use Reg 12 as base 
        XR    9,9                clear Reg 9 - divident value 
        LA    6,6                load divisor value 6 in Reg 6 
        LA    8,WTOLEN           address of WTO area in Reg 8 

LOOP DS 0H

        LA    9,1(,9)            add 1 to divident Reg 9 
        ST    9,FW2              store it 
        LM    4,5,FDOUBLE        load into even/odd register pair 
        STH   9,WTOTXT           store divident in text area 
        MVI   WTOTXT,X'F0'       first of two bytes zero 
        OI    WTOTXT+1,X'F0'     make second byte printable 
       WTO    TEXT=(8)           print it (Write To Operator macro) 
        DR    4,6                divide Reg pair 4,5 by Reg 6 
        LTR   5,5                test quotient (remainder in Reg 4) 
        BNZ   RETURN             if one: 6 iterations, exit loop. 
        B     LOOP               if zero: loop again. 

RETURN PR , return to caller. FDOUBLE DC 0FD

        DC    F'0' 

FW2 DC F'0' WTOLEN DC H'2' fixed WTO length of two WTOTXT DC CL2' '

        END   DOWHILE </lang>
Structured Macros

Although specified at the beginning (DO UNTIL), the test is done at the end of the loop (ENDDO). Structured macros (DO ENDDO) weren't in the 1963 standard of Assembler 360, but there are part of it since since 1998. <lang 360asm>* Do-While 27/06/2016 DOWHILE CSECT

        USING DOWHILE,12          set base register
        LR    12,15               init base register 
        SR    6,6                 v=0
        LA    4,1                 init reg 4
        DO UNTIL=(LTR,4,Z,4)      do until v mod 6=0
        LA    6,1(6)                v=v+1
        STC   6,WTOTXT              v
        OI    WTOTXT,X'F0'          make editable 
        WTO   MF=(E,WTOMSG)         display v
        LR    4,6                   v
        SRDA  4,32                  shift dividend to reg 5
        D     4,=F'6'               v/6  so r4=remain & r5=quotient
        ENDDO ,                   end do
        BR    14                  return to caller

WTOMSG DS 0F full word alignment for wto WTOLEN DC AL2(L'WTOTXT+4) length of WTO buffer

        DC    H'0'                must be zero

WTOTXT DS C one char

        END   DOWHILE</lang>

6502 Assembly

Code is called as a subroutine (i.e. JSR DoWhileSub). Specific OS/hardware routines for printing are left unimplemented. <lang 6502asm>DoWhileSub: PHA TYA PHA ;push accumulator and Y register onto stack

LDY #0 DoWhileLoop: INY JSR DisplayValue ;routine not implemented TYA SEC Modulus: SBC #6 BCS Modulus ADC #6 BNE DoWhileLoop

PLA TAY PLA ;restore Y register and accumulator from stack RTS ;return from subroutine</lang>

ActionScript

<lang actionscript>var val:int = 0; do {

   trace(++val);

} while (val % 6);</lang>

Ada

<lang ada>loop

  Value := Value + 1;
  Put (Value);
  exit when Value mod 6 = 0;

end loop;</lang> Here is an alternative version: <lang ada>for Value in 0..Integer'Last loop

  Put (Value);
  exit when Value mod 6 = 0;

end loop;</lang>

Agena

Tested with Agena 2.9.5 Win32 <lang agena>scope

   local i := 0;
   do
       inc i, 1;
       print( i )
   as ( i % 6 ) <> 0

epocs</lang>

Aime

<lang aime>integer a;

a = 0; do {

  a += 1;
  o_integer(a);
  o_byte('\n');

} while (a % 6 != 0);</lang>

ALGOL 60

Works with: ALGOL 60 version OS/360

No stuctured control instructions in Algol 60 to perform this task. Use of 2 harmful GOTOs. I agree Edsger Dijkstra communication "Go To Statement Considered Harmful", ACM 1968. <lang algol60>'BEGIN' 'COMMENT' Loops DoWhile - Algol60 - 22/06/2018;

 'INTEGER' I;
 I:=0;

LOOP:

   I:=I+1;
   'IF' I=I'/'6*6 'THEN' 'GOTO' LAB;
   OUTINTEGER(1,I);
 'GOTO' LOOP;

LAB: 'END'</lang>

Output:
         +1           +2           +3           +4           +5


ALGOL 68

<lang algol68>FOR value WHILE

 print(value);
  1. WHILE # value MOD 6 /= 0 DO
 SKIP

OD</lang>

ALGOL W

<lang algolw>begin

   integer i;
   i := 0;
   while
       begin
           i := i + 1;
           write( i );
           ( i rem 6 ) not = 0
       end
   do begin end

end.</lang>

AmigaE

<lang amigae>PROC main()

 DEF i = 0
 REPEAT
   i := i + 1
   WriteF('\d\n', i)
 UNTIL Mod(i, 6) = 0

ENDPROC</lang>

ARM Assembly

Works with: as version Raspberry Pi

<lang ARM Assembly>

/* ARM assembly Raspberry PI */ /* program loopdowhile.s */

/* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall

/*********************************/ /* Initialized data */ /*********************************/ .data szMessResult: .ascii "Counter = " @ message result sMessValeur: .fill 12, 1, ' '

                  .asciz "\n"

/*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program

   push {fp,lr}      @ saves 2 registers 
   mov r4,#0

1: @ begin loop

   mov r0,r4
   ldr r1,iAdrsMessValeur     @ display value
   bl conversion10             @ call function with 2 parameter (r0,r1)
   ldr r0,iAdrszMessResult
   bl affichageMess            @ display message
   add r4,#1                   @ increment counter
   mov r0,r4
   mov r1,#6              @ division conuter by 6
   bl division
   cmp r3,#0              @ remainder = zéro ?
   bne 1b                @ no ->begin loop one

100: @ standard end of the program

   mov r0, #0                  @ return code
   pop {fp,lr}                 @restaur 2 registers
   mov r7, #EXIT              @ request to exit program
   svc #0                       @ perform the system call

iAdrsMessValeur: .int sMessValeur iAdrszMessResult: .int szMessResult /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess:

   push {r0,r1,r2,r7,lr}      @ save  registres
   mov r2,#0                  @ counter length 

1: @ loop length calculation

   ldrb r1,[r0,r2]           @ read octet start position + index 
   cmp r1,#0                  @ if 0 its over 
   addne r2,r2,#1            @ else add 1 in the length 
   bne 1b                    @ and loop 
                               @ so here r2 contains the length of the message 
   mov r1,r0        			@ address message in r1 
   mov r0,#STDOUT      		@ code to write to the standard output Linux 
   mov r7, #WRITE             @ code call system "write" 
   svc #0                      @ call systeme 
   pop {r0,r1,r2,r7,lr}        @ restaur des  2 registres */ 
   bx lr                       @ return  

/******************************************************************/ /* Converting a register to a decimal */ /******************************************************************/ /* r0 contains value and r1 address area */ conversion10:

   push {r1-r4,lr}    @ save registers 
   mov r3,r1
   mov r2,#10

1: @ start loop

   bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
   add r1,#48        @ digit	
   strb r1,[r3,r2]  @ store digit on area
   sub r2,#1         @ previous position
   cmp r0,#0         @ stop if quotient = 0 */
   bne 1b	          @ else loop
   @ and move spaces in first on area
   mov r1,#' '   @ space	

2:

   strb r1,[r3,r2]  @ store space in area
   subs r2,#1       @ @ previous position
   bge 2b           @ loop if r2 >= zéro 

100:

   pop {r1-r4,lr}    @ restaur registres 
   bx lr	          @return

/***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10:

 /* r0 contains the argument to be divided by 10 */
   push {r2-r4}   /* save registers  */
   mov r4,r0 
   mov r3,#0x6667   @ r3 <- magic_number  lower
   movt r3,#0x6666  @ r3 <- magic_number  upper
   smull r1, r2, r3, r0   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) 
   mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */
   mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */
   add r0, r2, r1         /* r0 <- r2 + r1 */
   add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */
   sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */
   pop {r2-r4}
   bx lr                  /* leave function */

/***************************************************/ /* integer division unsigned */ /***************************************************/ division:

   /* r0 contains dividend */
   /* r1 contains divisor */
   /* r2 returns quotient */
   /* r3 returns remainder */
   push {r4, lr}
   mov r2, #0                @ init quotient
   mov r3, #0                @ init remainder
   mov r4, #32               @ init counter bits
   b 2f

1: @ loop

   movs r0, r0, LSL #1     @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
   adc r3, r3, r3           @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C 
   cmp r3, r1               @ compute r3 - r1 and update cpsr 
   subhs r3, r3, r1        @ if r3 >= r1 (C=1) then r3 ? r3 - r1 
   adc r2, r2, r2           @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C 

2:

   subs r4, r4, #1          @ r4 <- r4 - 1 
   bpl 1b                  @ if r4 >= 0 (N=0) then loop
   pop {r4, lr}
   bx lr

</lang>

AutoHotkey

<lang AutoHotkey>While mod(A_Index, 6) ;comment:everything but 0 is considered true

 output = %output%`n%A_Index%

MsgBox % output</lang>

AWK

<lang awk>BEGIN {

 val = 0
 do {
   val++
   print val
 } while( val % 6 != 0)

}</lang>

Axe

While Axe does not have explicit do-while loops, they can be easily emulated using an infinite loop with a conditional terminator: <lang axe>0→A While 1

A++
Disp A▶Dec,i

End!If A^6</lang>

BASIC

Works with: QuickBasic version 4.5

<lang qbasic>a = 0 do

 a = a + 1
 print a

loop while a mod 6 <> 0</lang>

BaCon

<lang freebasic>

a=0 REPEAT

   INCR a
   PRINT a

UNTIL MOD(a,6) == 0

</lang>

BBC BASIC

<lang bbcbasic>a = 0 REPEAT

 a = a + 1
 PRINT a

UNTIL a MOD 6 = 0</lang>

IS-BASIC

<lang IS-BASIC>100 LET I=0 110 DO 120 LET I=I+1 130 PRINT I 140 LOOP UNTIL MOD(I,6)=0</lang>

Sinclair ZX81 BASIC

<lang basic>10 LET X=0 20 LET X=X+1 30 PRINT X 40 IF X/6<>INT (X/6) THEN GOTO 20</lang>

bc

<lang bc>i = 0 for (;;) { ++i /* increments then prints i */ if (i % 6 == 0) break } quit</lang>

Befunge

<lang befunge>0>1+:.v

|%6: <
@</lang>

C

<lang c>int val = 0; do{

  val++;
  printf("%d\n",val);

}while(val % 6 != 0);</lang>

ChucK

<lang> 0 => int value; do {

   value++;
   <<<value>>>;

} while(value % 6 != 0); </lang>

C++

<lang cpp>int val = 0; do{

  val++;
  std::cout << val << std::endl;

}while(val % 6 != 0);</lang>

C#

<lang csharp>int a = 0;

do {

   a += 1;
   Console.WriteLine(a);

} while (a % 6 != 0);</lang>

Chapel

<lang chapel>var val = 0; do {

       val += 1;
       writeln(val);

} while val % 6 > 0;</lang>

Clipper

<lang clipper> Local n := 0

  DO WHILE .T.
     ? ++n
     IF n % 6 == 0
        EXIT
     ENDIF
  ENDDO</lang>

COBOL

The COBOL equivalent of a do-while loop is PERFORM WITH TEST AFTER UNTIL some-condition. <lang cobol> IDENTIFICATION DIVISION.

      PROGRAM-ID. loop-do-while.
      DATA DIVISION.
      WORKING-STORAGE SECTION.
      01  i PIC 99 VALUE 0.
      PROCEDURE DIVISION.
          PERFORM WITH TEST AFTER UNTIL FUNCTION MOD(i, 6) = 0
              ADD 1 TO i
              DISPLAY i
          END-PERFORM
          GOBACK
          .</lang>

Coco

Do-while loops are a JavaScript feature removed in CoffeeScript but re-added in Coco.

<lang coco>v = 0 do

  console.log ++v

while v % 6</lang>

CoffeeScript

CoffeeScript doesn't have do {} while () loop, but it can be emulated using loop statement and break unless statement. <lang coffeescript>val = 0 loop

 console.log ++val
 break unless val % 6</lang>

ColdFusion

<lang cfm><cfscript>

 value = 0;
 do
 {
   value += 1;
   writeOutput( value );
 } while( value % 6 != 0 );			

</cfscript></lang>

Common Lisp

<lang lisp>(let ((val 0))

 (loop do
       (incf val)
       (print val)
       while (/= 0 (mod val 6))))</lang>

loop can set up temporary values, and incf returns a value, so it's also possible to do

<lang lisp>(loop with val = 0

     do (print (incf val))
     until (= 0 (mod val 6)))</lang>

Clojure

<lang Clojure>(loop [i 0]

 (let [i* (inc i)]
   (println i*)
   (when-not (zero? (mod i* 6))
     (recur i*))))</lang>

D

<lang d>import std.stdio;

void main() {

   int val;
   do {
       val++;
       write(val, " ");
   } while (val % 6 != 0);

}</lang>

Output:
1 2 3 4 5 6 

dc

Translation of: bc

<lang dc>0 si [i = 0]sz [2Q]sA [A = code to break loop]sz [

li 1 + p	[print it = i + 1]sz
d si		[i = it, leave it on stack]sz
6 % 0 =A	[call A if 0 == it % 6]sz
0 0 =B		[continue loop]sz

]sB 0 0 =B</lang>

Delphi

<lang Delphi>program Loop;

{$APPTYPE CONSOLE}

var

 I: Integer;

begin

 I:= 0;
 repeat
   Inc(I);
   Write(I:2);
 until I mod 6 = 0;
 Writeln;
 Readln;

end.</lang>

Dragon

<lang dragon>val = 0 do{

  val++
  showln val

}while(val % 6 != 0)</lang>

DUP

DUP only provides a while loop in the form of [condition][block]#, where the block is executed in a loop as long as the condition is nonzero/true. A do-while loop is technically nothing more than executing the block once before running an ordinary while loop, so we simply define an operator or function that contains the block (comments in curly braces):

<lang DUP>[1+$.' ,]⇒A {operator definition: PUSH 1, ADD, DUP, print top of stack to SDTOUT, print whitespace} [1+$.' ,]a: {function definition}</lang>

and put the defined block in front of the while loop, and inside the while loop itself:

If the block was defined as an operator, the whole program would look like this (comments in curly braces):

<lang DUP>[1+$.' ,]⇒A 0 A[$6/%][A]# {PUSH 0, execute operator A, [DUP, PUSH 6, MOD/DIV, POP][execute operator A]#}</lang>

And if the block is defined as a named function:

<lang DUP>[1+$.' ,]a: 0 a;![$6/%][a;!]#</lang>

Result:

<lang DUP>1 2 3 4 5 6</lang>

DWScript

<lang Delphi> var i := 0;

repeat

  Inc(i);
  PrintLn(i);

until i mod 6 = 0; </lang> Bold text

E

E does not have an official do-while construct, but the primitive which loops are built out of (which calls a function which returns a boolean indicating whether it should be called again) can be used to construct a do-while. <lang e>var x := 0 __loop(fn {

   x += 1
   println(x)
   x % 6 != 0   # this is the return value of the function

})</lang>


Ela

<lang ela>open monad io

loop n | n % 6 == 0 = do return ()

      | else = do 
         putStrLn (show n)
         loop (n+1)

_ = loop 10 ::: IO</lang>

Elixir

<lang elixir>defmodule Loops do

 def do_while(n) do
   n1 = n + 1
   IO.puts n1
   if rem(n1, 6) == 0, do: :ok,
                     else: do_while(n1)
 end

end

Loops.do_while(0)</lang>

Emacs Lisp

The condition form for while can be a progn to evaluate arbitrary code before the loop condition. The body of a while can be empty.

<lang Lisp>(let ((val 0))

 (while (progn
          (setq val (1+ val))
          (message "%d" val)
          (/= 0 (mod val 6)))))</lang>

Erlang

<lang Erlang> do() -> do(0).

do(0) -> io:fwrite( "0 " ),

       do( 1 );

do(N) when N rem 6 =:= 0 -> io:format("~w~n", [N]); do(N) -> io:fwrite( "~p ", [N] ), do(N+1). </lang>

ERRE

<lang ERRE> A=0 REPEAT

 A=A+1
 PRINT(A)

UNTIL A MOD 6=0 !UNTIL A-6*INT(A/6)=0 for C-64 </lang>

Euphoria

Works with: Open Euphoria

<lang euphoria> include std/console.e include std/math.e

atom x = 0

loop do x += 1 ?x until(mod(x,6)) = 0 end loop

if getc(0) then end if </lang>

F#

If you must have a loop then this is acceptable F# <lang fsharp> let rec loop n =

 printfn "%d " n
 if (n+1)%6 > 0 then loop (n+1)

loop 0 </lang>

But I prefer this way: <lang fsharp> Seq.initInfinite id |> Seq.takeWhile(fun n->n=0 || n%6>0) |> Seq.iter (fun n-> printfn "%d" n) </lang>

Either produces:

Output:
0
1
2
3
4
5

Factor

<lang factor>0 [ dup 6 mod 0 = not ] [ [ . ] [ 1 + ] bi ] do while drop</lang>

Fantom

There is no do-while statement in Fantom, so instead use an infinite while loop with a break statement:

<lang fantom> class Main {

 public static Void main ()
 {
   i := 0
   while (true)
   {
     i += 1
     echo (i)
     if (i % 6 == 0) break // end loop on condition
   }
 }

} </lang>

Forth

<lang forth>: do-until

 0
 begin 1+
       dup .
       dup 6 mod 0=
 until
 drop ;</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran>INTEGER :: i = 0 DO

 i = i + 1
 WRITE(*, *) i
 IF (MOD(i, 6) == 0) EXIT

END DO</lang>

Works with: Fortran version 77 and later

<lang fortran> PROGRAM DOWHILE C Initialize modulus and value.

       INTEGER MODLUS, IVALUE
       PARAMETER (MODLUS = 6)
       IVALUE = 0

C FORTRAN 77 has no do-while structure -- not semantically. It is not C difficult to simulate it using GOTO, however:

  10   CONTINUE
         IVALUE = IVALUE + 1
         WRITE (*,*) IVALUE
       IF (.NOT. (MOD(IVALUE, MODLUS) .EQ. 0)) GOTO 10
       STOP
     END</lang>
Works with: Fortran version IV and later

<lang fortran> IVALUE = 0

  10 CONTINUE
       IVALUE=IVALUE+1
       WRITE(6,301) IVALUE
 301   FORMAT(I5)          
     IF(MOD(IVALUE,6).NE.0) GOTO 10
     END</lang>
Works with: Fortran version I and later

<lang fortran> IVALUE = 0

  10 IVALUE=IVALUE+1
     WRITE 301,IVALUE
 301 FORMAT(I5)          
     IF(IVALUE-IVALUE/6*6) 10,20,10
  20 STOP
     END</lang>

Fortress

Due to the way that Fortress works, you have to use a label to escape a loop upon a specified condition being met. There is no traditional break equivalent.

<lang fortress> component loops_do_while

 export Executable
 var x:ZZ32 = 0
 run() = label loop
   while true do
     x += 1
     println(x)
     if (x MOD 6) = 0
     then exit loop
     end
   end
 end loop

end </lang>

Output:
1
2
3
4
5
6

FreeBASIC

<lang freebasic>' FB 1.05. 0 Win64

Dim i As Integer = 0 Do

 i += 1
 Print i; " ";

Loop While i Mod 6 <> 0 Print Sleep</lang>

Output:
 1  2  3  4  5  6

Frink

<lang frink>n = 0 do {

  n = n + 1
  println[n]

} while n mod 6 != 0</lang>

FutureBasic

<lang futurebasic> include "ConsoleWindow"

dim as long i

do

 i++
 print i

until ( i mod 6 == 0 ) </lang> Output:

 1
 2
 3
 4
 5
 6

Gambas

Click this link to run this code <lang gambas>Public Sub Main() Dim siCount As Short

Repeat

 Inc siCount
 Print siCount;;

Until siCount Mod 6 = 0

End</lang> Output:

1 2 3 4 5 6

GAP

<lang gap>n := 0; repeat

   n := n + 1;
   Print(n, "\n");

until RemInt(n, 6) = 0;</lang>

Go

There is no explicit do-while in Go, but it can be simulated with a range-based for loop and the break statement. <lang go>package main

import "fmt"

func main() { var value int for { value++ fmt.Println(value)

               if value%6 != 0 {
                       break
               }

} }</lang>

Output:
1
2
3
4
5
6

It can also be simulated without using a break statement as follows: <lang go>package main

import "fmt"

func main() { var value int for ok := true; ok; ok = value%6 != 0 { value++ fmt.Println(value) } }</lang>

Output:
Same as before.

GML

<lang GML>i = 0 do

   {
   i += 1
   show_message(string(i))
   }

until (i mod 6 = 0)</lang>

Groovy

Groovy does not have a bottom-checking loop construct! So use an "infinite" while loop with a conditional break as the last statement <lang groovy>def i = 0 while (true) {

   i++
   println i
   if ( i % 6 == 0) break

}</lang>

Output:
1
2
3
4
5
6

GW-BASIC

GW-BASIC does not have a do .. while construct. Equivalent using WHILE:

Works with: PC-BASIC version any

<lang qbasic> 10 LET I% = 0 20 ' first iteration - before the WHILE 30 PRINT I% 40 LET I% = I% + 1 50 WHILE I% MOD 6 <> 0 60 PRINT I% 70 LET I% = I% + 1 80 WEND </lang> Equivalent using GOTO:

Works with: PC-BASIC version any

<lang qbasic> 10 LET I% = 0 20 PRINT I% 30 LET I% = I% + 1 40 IF I% MOD 6 <> 0 THEN GOTO 20 </lang>

Harbour

<lang visualfoxpro>LOCAL n := 0

DO WHILE .T.

  ? ++n
  IF n % 6 == 0
     EXIT
  ENDIF

ENDDO</lang>

Haskell

<lang haskell>import Data.List import Control.Monad import Control.Arrow

doWhile p f n = (n:) $ takeWhile p $ unfoldr (Just.(id &&& f)) $ succ n</lang> Example executed in GHCi: <lang haskell>*Main> mapM_ print $ doWhile ((/=0).(`mod`6)) succ 0 0 1 2 3 4 5</lang>

The standard Prelude also includes, without further import or definition, an until function, which takes three arguments – a predicate function, a transformation function, and an initial value.

<lang haskell>main :: IO () main =

 mapM_ print . reverse $
 until
   (\(x:_) -> (x > 0) && (mod x 6 == 0)) 
   (\xs@(x:_) -> succ x : xs) 
   [0]</lang>
Output:
0
1
2
3
4
5
6

With mutable references

Using iterateWhile from monad-loops package <lang haskell>import Data.IORef import Control.Monad.Loops

main = do

 x <- newIORef 0;
 iterateWhile (\val -> val `mod` 6 /= 0 ) $ do
   modifyIORef x (+1)
   val <- readIORef x
   print val
   return val</lang>

HolyC

<lang holyc>U8 i = 0; do {

  i++;
  Print("%d\n", i);

} while (i % 6 != 0);</lang>

Icon and Unicon

Icon and Unicon do not have a do-while looping control with end of loop checking. There are four looping controls 'every', 'repeat', 'until', and 'while' (see Introduction to Icon and Unicon/Looping Controls for more information.) <lang Icon>procedure main()

i := 0 repeat {

  write(i +:= 1)
  if i % 6 = 0 then break
  }

end</lang>

J

J is array-oriented, so there is very little need for loops. For example, one could satisfy this task this way:

  ,. ([^:(0=6|])>:)^:a: 0

J does support loops for those times they can't be avoided (just like many languages support gotos for those time they can't be avoided). <lang j>3 : 0 ] 0

        NB.  The 'st' in 'whilst' stands for 'skip test'
        whilst. 0 ~: 6 | y do.  
            y 1!:2 ]2 
            y =. y+1
        end.
       i.0 0
  )</lang>

Though it's rare to see J code like this.

Java

<lang java>int val = 0; do{

  val++;
  System.out.println(val);

}while(val % 6 != 0);</lang>

JavaScript

Javascript: Imperative

<lang javascript>var val = 0; do {

 print(++val);

} while (val % 6);</lang>

Javascript: Functional

ES5

In a functional idiom of JavaScript we cannot use a Do While statement, as it returns no value and is not a composable expression. We can, however achieve the same effect with a composable doWhile function, which takes three arguments, and returns the output series as a value.

  1. An initial value,
  2. a Do function which transforms that value repetitively, corresponding to the body of the loop,
  3. and a conditional While function.

<lang JavaScript>function doWhile(varValue, fnBody, fnTest) {

 'use strict';
 var d = fnBody(varValue); // a transformed value
 return fnTest(d) ? [d].concat(
   doWhile(d, fnBody, fnTest)
 ) : [d];

}

console.log(

 doWhile(0,           // initial value
   function (x) {     // Do body, returning transformed value
     return x + 1;
   },
   function (x) {     // While condition
     return x % 6;
   }
 ).join('\n')

);</lang>

Output: <lang JavaScript>1 2 3 4 5 6</lang>

Alternatively, if we assume instead that the unstated problem was not to produce repetitive computation, but to derive the membership of a set we could interpret the task as a request for a JavaScript implementation of the takeWhile function – a familiar staple of functional list processing.

So, for example, something like:

<lang JavaScript>function range(m, n) {

 'use strict';
 return Array.apply(null, Array(n - m + 1)).map(
   function (x, i) {
     return m + i;
   }
 );

}

function takeWhile(lst, fnTest) {

'use strict';
 var varHead = lst.length ? lst[0] : null;

 return varHead ? (
   fnTest(varHead) ? [varHead].concat(
     takeWhile(lst.slice(1), fnTest)
   ) : []
 ) : []

}

console.log(

 takeWhile(
   range(1, 100),
   function (x) {
     return x % 6;
   }
 ).join('\n')

);</lang>

Output: <lang JavaScript>1 2 3 4 5</lang>

ES6

A process or value of this kind might be better expressed (in functionally composed JavaScript) with an unfold or until function, returning a list.

<lang JavaScript>(() => {

   'use strict';
   // unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
   function unfoldr(mf, v) {
       for (var lst = [], a = v, m;
           (m = mf(a)) && m.valid;) {
           lst.push(m.value), a = m.new;
       }
       return lst;
   }
   // until :: (a -> Bool) -> (a -> a) -> a -> a
   function until(p, f, x) {
       let v = x;
       while(!p(v)) v = f(v);
       return v;
   }
   let result1 = unfoldr(
       x => {
           return {
               value: x,
               valid: (x % 6) !== 0,
               new: x + 1
           }
       },
       1
   );
   let result2 = until(
       m => (m.n % 6) === 0,
       m => {
           return {
               n : m.n + 1,
               xs : m.xs.concat(m.n)
           };
       },
       {
           n: 1,
           xs: []
       }
   ).xs;
   
   return [result1, result2];

})(); </lang>


<lang JavaScript>[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]</lang>

ES6 is a superset of Javascript so the Javascript and ES5 solution is valid. An example of a do-while loop in a generator follows that produces correct output:

<lang JavaScript> // generator with the do while loop function* getValue(stop) {

   var i = 0;
   do {
       yield ++i;
   } while (i % stop != 0);

}

// function to print the value and invoke next function printVal(g, v) {

   if (!v.done) {
       console.log(v.value);
       setImmediate(printVal, g, g.next());
   }

}

(() => {

   var gen = getValue(6);
   printVal(gen, gen.next());

})(); </lang>

<lang JavaScript> 1 2 3 4 5 6 </lang>

jq

Works with: jq version 1.4

In jq 1.4, the "recurse" built-in always emits the input value, and so to accomplish the task specified here, we shall define a control structure: "do_while(action; condition)" as follows: <lang jq># Perform the action, then check the condition, etc def do_while( action; condition ):

 def w: action | if (condition | not) then empty else ., w end;
 w;</lang>

The task: <lang jq>0 | do_while( .+1; . % 6 != 0 )</lang>

Output:
1
2
3
4
5

Julia

Julia has no do-while construct. Here is one of several ways to implement do-while behavior.

<lang Julia> julia> i = 0 0

julia> while true

          println(i)
          i += 1
          i % 6 == 0 && break
      end

0 1 2 3 4 5 </lang>

Using a macro that mimics the classic C style do-while.

Notice that the symbol while cannot be used as it is a keyword, which is why when is used instead, also the macro definition is wrapped in a @eval macro invocation since do is also a keyword, but in Julia macro calls are prefixed by @ so this is only an issue during the macro definition, not when invoked, ie. @do block when condition).

<lang Julia> julia> @eval macro $(:do)(block, when::Symbol, condition)

          when ≠ :when && error("@do expected `when` got `$s`")
          quote
              let
                  $block
                  while $condition
                      $block
                  end
              end
          end |> esc
      end

@do (macro with 1 method)

julia> i = 0 0

julia> @do begin

          @show i
          i += 1
      end when i % 6 ≠ 0

i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 </lang>

Here is mostly the same macro, but with the conditional clause used first, which is arguably more readable.

<lang Julia> julia> macro do_while(condition, block)

          quote
              let
                  $block
                  while $condition
                      $block
                  end
              end
          end |> esc
      end

@do_while (macro with 1 method)

julia> i = 0 0

julia> @do_while i % 6 ≠ 0 begin

          @show i
          i += 1
      end

i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 </lang>

Kotlin

<lang scala>// version 1.0.6

fun main(args: Array<String>) {

   var value = 0
   do {
       println(++value)
   }
   while (value % 6 != 0)

}</lang>

Output:
1
2
3
4
5
6

LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

Lasso

<lang Lasso>local(x = 0) while(#x % 6 > 0 || #x == 0) => {^ ++#x '\r' // for formatting ^}</lang>

Liberty BASIC

<lang lb> a = 0 do

 a =a +1
 print a

loop until ( a mod 6) = 0 </lang>

Lingo

Lingo has no do..while, but here how this behavior can be implemented: <lang lingo>i = 0 repeat while TRUE

 i = i+1
 put i
 if i mod 6 = 0 then exit repeat

end</lang>

Lisaac

<lang Lisaac>+ val : INTEGER; {

 val := val + 1;
 val.print;
 '\n'.print;
 val % 6 != 0

}.while_do { };</lang>

LiveCode

<lang LiveCode>repeat while n mod 6 is not 0 or n is 0

   add 1 to n
   put n

end repeat</lang>

Lua

Lua doesn't have a do .. while construct.

<lang lua> i=0 repeat

 i=i+1
 print(i)

until i%6 == 0 </lang>

<lang logo>make "val 0 do.while [make "val :val + 1 print :val] [notequal? 0 modulo :val 6] do.until [make "val :val + 1 print :val] [equal? 0 modulo :val 6]

to my.loop :n

 make "n :n + 1
 print :n
 if notequal? 0 modulo :n 6 [my.loop :n]

end my.loop 0</lang>

M2000 Interpreter

<lang M2000 Interpreter> Module checkit {

     x=0
     \\ Do or Repeat
     Do {
           x++
           Print x
     } Until x mod 6=0 
    
     x=0
     {
           \\ when enter to block the loop flag change to false
           x++
           if x mod 6<>0 Then loop   ' set loop flag of current block to true
           \\ when block end check Loop flag and if true execute block again
           Print X
     }

} Checkit </lang>

Output:
1
2
3
4
5
6
1
2
3
4
5
6

Maple

<lang Maple>val := 0: do

       val := 1 + val;
       print( val );
       if irem( val, 6 ) = 0 then
               break
       end if;

end do:</lang>

Mathematica

Because everything is an expression in Mathematica, While[body;condition] tests condition after body has been executed at least once. <lang Mathematica>value = 0; While[

value++;
Print[value];
Mod[value,6]!=0

]</lang>

MATLAB / Octave

<lang Matlab> a=0;

  while (1) 
     a = a+1; 
     disp(a);
  if (~mod(a,6)) break; end; 	
  end; </lang>

Maxima

<lang maxima>block([n: 0], do (ldisp(n: n + 1), if mod(n, 6) = 0 then return('done)))$</lang>

MAXScript

<lang maxscript>a = 0 do (

   print a
   a += 1

) while mod a 6 != 0</lang>

Metafont

Metafont has no a do-while construct; the same thing can be done using a forever loop and exitif.

<lang metafont>a := 0; forever: show a; a := a + 1; exitif a mod 6 = 0; endfor end</lang>

Microsoft Small Basic

Microsoft Small Basic does not have a do .. while construct. Equivalent using While: <lang microsoftsmallbasic> i = 0 ' first iteration - before the While TextWindow.WriteLine(i) i = i + 1 While Math.Remainder(i, 6) <> 0

 TextWindow.WriteLine(i)
 i = i + 1

EndWhile </lang> Equivalent using Goto: <lang microsoftsmallbasic> i = 0 loopStart: TextWindow.WriteLine(i) i = i + 1 If Math.Remainder(i, 6) <> 0 Then

 Goto loopStart

EndIf </lang>

MIPS Assembly

<lang mips> .text main: li $s0, 0 # start at 0. li $s1, 6 loop: addi $s0, $s0, 1 # add 1 to $s0 div $s0, $s1 # divide $s0 by $s1. Result is in the multiplication/division registers mfhi $s3 # copy the remainder from the higher multiplication register to $s3 move $a0, $s0 # variable must be in $a0 to print li $v0, 1 # 1 must be in $v0 to tell the assembler to print an integer syscall # print the integer in $a0 bnez $s3, loop # if $s3 is not 0, jump to loop

li $v0, 10 syscall # syscall to end the program </lang>

МК-61/52

<lang>0 П4 КИП4 ИП4 6 / {x} x=0 02 С/П</lang>

Modula-2

<lang modula2>MODULE DoWhile;

 IMPORT InOut;
 VAR
   i: INTEGER;

BEGIN

 i := 0
 REPEAT
   InOut.WriteInt(i, 1);
   InOut.WriteLn;
   INC(i)
 UNTIL i MOD 6 = 0;

END DoWhile.</lang>

Modula-3

This is very similar to the Modula-2 code above. <lang modula3>REPEAT

 i := i + 1;
 IO.Put(Fmt.Int(i));

UNTIL i MOD 6 = 0;</lang>

Monicelli

The do-while loop is the only kind of loop available in Monicelli <lang monicelli> stuzzica

   ...     # loop body

e brematura anche, se <expr> # exit if <expr> is false </lang>

MUMPS

<lang MUMPS>DOWHILELOOP

   set val = 0    
   do {
       set val = val + 1
       write val,!
   } while ((val # 6) '= 0)
   
   quit</lang>
Output:

SAMPLES>do ^DOWHILELOOP 1 2 3 4 5 6

Neko

<lang ActionScript>/**

Loops/Do-while in Neko
Tectonics:
  nekoc loops-do-while.neko
  neko loops-do-while
  • /

var index = 0; do {

 index += 1;
 $print(index, "\n");

} while (index % 6) != 0</lang>

Output:
prompt$ nekoc loops-do-while.neko
prompt$ neko loops-do-while
1
2
3
4
5
6

Nemerle

<lang Nemerle>mutable x = 0; do {

   x++;
   WriteLine($"$x");

} while (x % 6 != 0)</lang>

NetRexx

In NetRexx the do–while construct is implemented via the until expru conditional clause of the loop instruction. The expression expru in the until expru clause is evaluated at the end of the loop, guaranteeing that the loop will be executed at least once. <lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols nobinary

 say
 say 'Loops/Do-while'
 i_ = 0
 loop until i_ // 6 = 0
   i_ = i_ + 1
   say i_
   end

</lang>

NewLISP

<lang NewLISP>(let ((i 0))

 (do-until (= 0 (% i 6))

(println (++ i))))</lang>

Nim

Nim does not have a do-while loop, but it's easy to write your own: <lang nim>template doWhile(a, b: untyped): untyped =

 b
 while a:
   b

var val = 1 doWhile val mod 6 != 0:

 val += 1
 echo val</lang>

NS-HUBASIC

<lang NS-HUBASIC>10 PRINT "NO,"A" ISN'T A MULTIPLE OF 6." 20 A=A+1 30 IF A-(A/6)*6<>0 THEN GOTO 10 40 PRINT "YES, 6 IS A MULTIPLE OF 6."</lang>

Oberon-2

Works with oo2c Version 2 <lang oberon2> MODULE LoopDoWhile; IMPORT

 Out;

PROCEDURE Do(); VAR

 i: INTEGER;

BEGIN

 i := 0;
 REPEAT
   Out.LongInt(i,0);Out.Ln;
   INC(i)    
 UNTIL (i MOD 6 = 0);

END Do;

BEGIN

 Do

END LoopDoWhile. </lang>

OCaml

OCaml doesn't have a do-while loop, so we can just make a local loop: <lang ocaml>let rec loop i =

 let i = succ i in
 Printf.printf "%d\n" i;
 if i mod 6 <> 0 then
   loop i
 in
 loop 0</lang>

or implementing a generic do-while iterator with higher order function:

<lang ocaml>let do_while f p =

 let rec loop() =
   f();
   if p() then loop()
 in
 loop()

(** val do_while : (unit -> 'a) -> (unit -> bool) -> unit *)</lang>

<lang ocaml>let v = ref 0 in do_while (fun () -> incr v; Printf.printf "%d\n" !v)

        (fun () -> !v mod 6 <> 0)</lang>

The example above is the an imperative form, below is its functional counterpart: <lang ocaml>let do_while f p ~init =

 let rec loop v =
   let v = f v in
   if p v then loop v
 in
 loop init

do_while (fun v ->

           let v = succ v in
           Printf.printf "%d\n" v;
           (v))
        (fun v -> v mod 6 <> 0)
        ~init:0</lang>

Or in a very poor OCaml style, we can use an exception to exit a while loop: <lang ocaml>let v = ref 0 exception Exit_loop try while true do

 incr v;
 Printf.printf "%d\n" !v;
 if not(!v mod 6 <> 0) then
   raise Exit_loop;

done with Exit_loop -> ()</lang>

Objeck

<lang objeck> i := 0; do {

  i += 1;
  i->PrintLine();

} while (i % 6 <> 0); </lang>

Octave

The do-while can be changed into a do-until, just negating the condition of the while. <lang octave>val = 0; do

 val++;
 disp(val)

until( mod(val, 6) == 0 )</lang>

Oforth

<lang Oforth>0 doWhile: [ 1+ dup . dup 6 rem 0 <> ] drop</lang>

OpenEdge/Progress

<lang progress>DEFINE VARIABLE ii AS INTEGER.

DO WHILE ii MODULO 6 <> 0 OR ii = 0:

  ii = ii + 1.
  MESSAGE ii VIEW-AS ALERT-BOX.

END.</lang>

Oz

Normal Oz variables are single-assignment only. So we use a "cell", which is a one-element mutable container. <lang oz>declare

 I = {NewCell 0}

in

 for until:@I mod 6 == 0 do
    I := @I + 1
    {Show @I}
 end</lang>

PARI/GP

The generic Pari loops (while, until) test at the beginning, so just use an infinite loop with a break. <lang parigp>x = 0; while(1,

 print(x++);
if(x % 6 == 0, break)

)</lang>

If the loop body is something simple then it might be worked into the loop condition. This is obscure but compact.

<lang parigp>x = 0; while (print(x++) || x % 6, )</lang>

The condition in while and until is an expression, not a sequence, so ; for multiple statements cannot be used there.

Pascal

<lang pascal>program countto6(output);

var

 i: integer;

begin

 i := 0;
 repeat
   i := i + 1;
   writeln(i)
 until i mod 6 = 0

end.</lang>

Perl

<lang perl>my $val = 0; do {

  $val++;
  print "$val\n";

} while ($val % 6);</lang> do ... until (condition) is equivalent to do ... while (not condition). <lang perl>my $val = 0; do {

  $val++;
  print "$val\n";

} until ($val % 6 == 0);</lang>

Perl 6

Works with: Rakudo Star version 2010.08

<lang perl6>my $val = 0; repeat {

   say ++$val;

} while $val % 6;</lang>

repeat ... until condition is equivalent to do ... while not condition.

<lang perl6>my $val = 0; repeat {

   say ++$val;

} until $val %% 6;</lang> (Here we've used %%, the "divisible-by" operator.)

You can also put the condition before the block, without changing the order of evaluation. <lang perl6>my $val = 0; repeat while $val % 6 { say ++$val; }</lang>

Phix

<lang Phix>integer x = 0 while 1 do

   x += 1
   ?x
   if mod(x,6)=0 then exit end if

end while</lang>

PHL

<lang phl>var i = 0; do { i = i::inc; printf("%i\n", i); } while (i%6 != 0);</lang>

PHP

<lang php>$val = 0; do {

  $val++;
  print "$val\n";

} while ($val % 6 != 0);</lang>

PicoLisp

Literally: <lang PicoLisp>(let Val 0

  (loop
     (println (inc 'Val))
     (T (=0 (% Val 6))) ) )</lang>

Shorter: <lang PicoLisp>(let Val 0

  (until (=0 (% (println (inc 'Val)) 6))) )</lang>

or: <lang PicoLisp>(for (Val 0 (n0 (% (println (inc 'Val)) 6))))</lang>

Pike

<lang pike>int main(){

  int value = 0;
  do {
     value++;
     write(value + "\n");
  } while (value % 6);

}</lang>

PL/I

<lang pli> dcl value fixed bin (31) init (0); do forever;

 value = value + 1;                   
                                      
 if mod(value, 6) = 0 then            
   leave;                             
                                      
 put list (value);                    

end; </lang> or shorter: <lang pli>

dcl value fixed bin(31) init(0);
do Until(value=6);
  value+=1;
  put Skip list(value);
end;</lang>
Output:
             1
             2
             3
             4
             5
             6     

Pop11

<lang pop11>lvars val = 0; while true do

  val + 1 -> val;
  printf(val, '%p\n');
  quitif(val rem 6 = 0);

endwhile;</lang>

PowerShell

<lang powershell>$n = 0 do {

   $n++
   $n

} while ($n % 6 -ne 0)</lang>

Prolog

<lang prolog> % initial condition do(0):- write(0),nl,do(1).

% control condition do(V):- 0 is mod(V,6), !, fail.

% loop do(V) :-

   write(V),nl,
   Y is V + 1,
   do(Y).

wloop :-

  do(0).

</lang>

PureBasic

Works with: PureBasic version 4.41

<lang PureBasic>x=0 Repeat

 x+1
 Debug x

Until x%6=0</lang>

Python

Python doesn't have a do-while loop. <lang python>val = 0 while True:

  val +=1
  print val
  if val % 6 == 0: break</lang>

or repeat the body of the loop before a standard while. <lang python>val = 1 print val while val % 6 != 0:

  val += 1
  print val</lang>

R

<lang R>i <- 0 repeat {

  i <- i + 1
  print(i)
  if(i %% 6 == 0) break

}</lang>

Racket

Idiomatic Racket code is functional: <lang racket>

  1. lang racket

(let loop ([n 0])

 (let ([n (add1 n)])
   (displayln n)
   (unless (zero? (modulo n 6)) (loop n))))

</lang>

But an imperative version is easy to do too: <lang racket>

  1. lang racket

(define n 0) (let loop ()

 (set! n (add1 n))
 (displayln n)
 (unless (zero? (modulo n 6)) (loop)))

</lang>

REBOL

<lang REBOL>REBOL [ Title: "Loop/While" URL: http://rosettacode.org/wiki/Loop/Do_While ]

REBOL doesn't have a specific 'do/while' construct, but 'until' can
be used to provide the same effect.

value: 0 until [ value: value + 1 print value

0 = mod value 6 ]</lang>

Output:
1
2
3
4
5
6

Red

<lang Red>Red [] i: 0 until [

 ?? i
 i: i + 1
 i % 6 = 0 ;; loop , until this is true...

]

</lang>

Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5

REXX

In the DO UNTIL construct, the expression is evaluated at the end of the DO loop,
even though it is written at the beginning.
This insures that the DO UNTIL loop will execute at least once (as coded below).

In contrast, a DO WHILE construct, the expression would be evaluated at the beginning of the DO loop, and
may cause the DO WHILE loop to not execute at all.
This necessitates the use of DO UNTIL instead of DO WHILE.

version 1

<lang rexx>/*REXX program demonstrates a DO UNTIL construction. */ v=0

         do  until  v//6==0           /*REXX   //   is the ÷ remainder.*/
         v=v+1
         say v
         end
                                      /*stick a fork in it, we're done.*/</lang>
Output:
1
2
3
4
5
6

version 2

<lang rexx>/*REXX program demonstrates a DO UNTIL construction. */

         do v=1  until  v//6==0       /*REXX   //   is the ÷ remainder.*/
         say v
         end
                                      /*stick a fork in it, we're done.*/</lang>

output is the same as the 1st version.

Ring

<lang ring>

  n = 0
  While True
     n++  See n + nl
     if n % 6 = 0  exit ok
  end

</lang>

Ruby

The while statement modifier normally checks the condition before entering the loop. But if the while statement modifier is on a begin ... end statement, then it loops at least once. Same with the until statement modifier.

while until
<lang ruby>val = 0

begin

  val += 1
  puts val

end while val % 6 != 0</lang>

<lang ruby>val = 0

begin

  val += 1
  puts val

end until val % 6 == 0</lang>

During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.

break unless break if
<lang ruby>val = 0

loop do

  val += 1
  puts val
  break unless val %6 != 0

end</lang>

<lang ruby>val = 0

loop do

  val += 1
  puts val
  break if val %6 == 0

end</lang>

All four of these examples print the numbers 1, 2, 3, 4, 5, 6.

Rust

Rust does not have a do...while loop. Instead, the keyword loop is used with a termination condition.

<lang rust>let mut x = 0;

loop {

   x += 1;
   println!("{}", x);
   if x % 6 == 0 { break; }

}</lang>

Salmon

<lang Salmon>variable x := 0; do

 {
   ++x;
   x!
 }

while (x % 6 != 0);</lang>

SAS

<lang sas>/* using DO UNTIL so that the loop executes at least once */ data _null_; n=0; do until(mod(n,6)=0);

   n+1;
   put n;

end; run;</lang>

Sather

Translation of: C

<lang sather>class MAIN is

 main is
   val ::= 0;
   loop
     val := val + 1;
     #OUT + val + "\n";
     while!(val % 6 /= 0)
   end;
 end;

end;</lang>

Scala

Library: Scala

Imperative

<lang scala> {

   var (x, l) = (0, List[Int]())
   do {
     x += 1
     l :+= x // A new copy of this list with List(x) appended.
   } while (x % 6 != 0)
   l
 }.foreach(println(_))

</lang>

Tail recursive

<lang scala> def loop(iter: Int, cond: (Int) => Boolean, accu: List[Int]): List[Int] = { val succ = iter + 1 val temp = accu :+ succ if (cond(succ)) loop(succ, cond, temp) else temp } println(loop(0, (_ % 6 != 0), Nil))</lang>

Stream

<lang scala> def loop(i: Int, cond: (Int) => Boolean): Stream[Int] = {

   val succ = i + 1;
   succ #:: (if (cond(succ)) loop(succ, cond) else Stream.empty)
 }
 loop(0, (_ % 6 != 0)).foreach(println(_))</lang>

Scheme

<lang scheme>(let loop ((i 1))

 (display i)
 (if (positive? (modulo i 6))
     (loop (+ i 1))))</lang>

Scilab

Works with: Scilab version 5.5.1

<lang>v=0 while %T

   v=v+1
   printf("%2d ",v)
   if modulo(v,6)==0 then break; end

end printf("\n")</lang>

Output:
 1  2  3  4  5  6 

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 local
   var integer: number is 0;
 begin
   repeat
     incr(number);
     writeln(number)
   until number rem 6 = 0
 end func;</lang>

Sidef

<lang ruby>var value = 0; do {

   say ++value;

} while (value % 6);</lang>

Slate

<lang slate>[| val |

 val: 0.
 [val: val + 1.
  print: val.
  val \\ 6 ~= 0] whileTrue

] do.</lang>

Smalltalk

Works with: Smalltalk/X

<lang smalltalk>|val| val := 0. [

 val := val + 1.
 val displayNl.

] doWhile: [ (val rem: 6) ~= 0 ]</lang>

<lang smalltalk>|val| val := 0. [

 val := val + 1.
 val displayNl.

] doUntil: [ (val rem: 6) == 0 ]</lang>

Works with: GNU Smalltalk

To simulate the do-while construct, we can use the whileTrue: method of a block with a void while block. <lang smalltalk>|val| val := 0. [

 val := val + 1.
 val displayNl.
 (val rem: 6) ~= 0

] whileTrue: [ ]</lang>

Sparkling

<lang sparkling>var i = 0; do {

   print(++i);

} while (i % 6 != 0);</lang>

Spin

Works with: BST/BSTC
Works with: FastSpin/FlexSpin
Works with: HomeSpun
Works with: OpenSpin

<lang spin>con

 _clkmode = xtal1 + pll16x
 _clkfreq = 80_000_000

obj

 ser : "FullDuplexSerial.spin"

pub main | n

 ser.start(31, 30, 0, 115200)
 n := 0
 repeat
   n += 1
   ser.dec(n)
   ser.tx(32)
 while n // 6
 waitcnt(_clkfreq + cnt)
 ser.stop
 cogstop(0)</lang>
Output:
1 2 3 4 5 6 

SPL

<lang spl>n = 0 >

 n += 1
 #.output(n)

< n%6</lang>

Output:
1
2
3
4
5
6

Stata

Stata macro language has no do/while loop, but it's possible to achieve this with a while loop.

Use a flag to force the first loop. It's changed in the loop so that it will have no effect after the first loop.

<lang stata>local n 0 local q 1 while `q' | mod(`n',6) { local q 0 di `++n' }</lang>

Use an infinite while loop and do the test with an if' at the end of the loop.

<lang stata>local n 0 while 1 { di `++n' if mod(`n',6)==0 continue, break }</lang>

Mata

Mata has a do/while loop:

<lang>mata n=0 do { printf("%f\n",++n) } while (mod(n,6)) end</lang>

Suneido

<lang Suneido>val = 0 do

   {
   Print(++val)
   } while (val % 6 isnt 0)</lang>
Output:
1
2
3
4
5
6

Swift

Works with: Swift version 3.x+

<lang swift>var val = 0 repeat {

 val += 1
 print(val)

} while val % 6 != 0</lang>

Works with: Swift version 2.x

<lang swift>var val = 0 repeat {

 val++
 print(val)

} while val % 6 != 0</lang>

Works with: Swift version 1.x

<lang swift>var val = 0 do {

  val++
  println(val)

} while val % 6 != 0</lang>

Tcl

Tcl does not have a built-in do...while construct. This example demonstrates the ease of creating new looping contructs in plain Tcl. do procedure taken from Tcler's wiki <lang tcl>proc do {body keyword expression} {

   if {$keyword eq "while"} {
      set expression "!($expression)"
   } elseif {$keyword ne "until"} {
      return -code error "unknown keyword \"$keyword\": must be until or while"
   }
   set condition [list expr $expression]
   while 1 {
      uplevel 1 $body
      if {[uplevel 1 $condition]} {
         break
      }
   }
   return

}

set i 0 do {puts [incr i]} while {$i % 6 != 0}</lang>

Library: Tcllib (Package: control)

<lang tcl>package require control set i 0; control::do {puts [incr i]} while {$i % 6 != 0} set i 0; control::do {puts [incr i]} until {$i % 6 == 0}</lang>

Mind you, it is also normal to write this task using a normal while as: <lang tcl>set i 0 while true {

   puts [incr i]
   if {$i % 6 == 0} break

}</lang>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT var=0 LOOP var=var+1, rest=var%6 PRINT var IF (rest==0) EXIT ENDLOOP </lang>

Output:
1
2
3
4
5
6

UNIX Shell

Works with: bash
Works with: pdksh
Works with: zsh

<lang bash>val=0 while true; do

 echo $((++val))
 [ $((val%6)) -eq 0 ] && break

done</lang>

Works with: Bourne Shell

<lang bash>val=0 while true; do

 val=`expr $val + 1`
 echo $val
 expr $val % 6 = 0 >/dev/null && break

done</lang>

Works with: zsh

<lang bash>for ((val=1;;val++)) {

 print $val
 (( val % 6 )) || break

}</lang>

Vala

<lang vala> int a = 0;

 do {
   a++;
   print(a.to_string() + "\n");
 } 
 while ( a % 6 != 0);

</lang>

VBA

<lang VB>Public Sub LoopDoWhile()

   Dim value As Integer
   value = 0
   Do
       value = value + 1
       Debug.Print value;
   Loop While value Mod 6 <> 0

End Sub</lang>

Output:
 1  2  3  4  5  6 

Vedit macro language

<lang vedit>#1 = 0 do {

   #1++
   Num_Type(#1)

} while (#1 % 6 != 0);</lang>

Verbexx

<lang verbexx>// Basic @LOOP until: verb

@LOOP init:{@VAR n = 0} until:(n % 6 == 0) {

    n++;
    @SAY n; 

};</lang>

Visual Basic .NET

<lang vbnet>Dim i = 0 Do

   i += 1
   Console.WriteLine(i)

Loop Until i Mod 6 = 0</lang>

XPL0

<lang XPL0>code CrLf=9, IntOut=11; int V; [V:= 0; repeat V:= V+1;

       IntOut(0, V);  CrLf(0);

until rem(V/6) = 0; ]</lang>

Yorick

<lang yorick>val = 0; do {

   val++;
   write, val;

} while(val % 6 != 0);</lang>

zkl

Translation of: Yorick

<lang zkl>val := 0; do {

   val+=1;
   val.print(" ");

} while(val % 6 != 0);</lang>

Output:
1 2 3 4 5 6