Loops/Break: Difference between revisions

85,932 bytes added ,  2 months ago
No edit summary
 
(334 intermediate revisions by more than 100 users not shown)
Line 1:
{{task|Iteration}} [[Category:Loop modifiers]] [[Category:Simple]]
{{task|Iteration}}Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never generated as the first number in a loop, loop forever.
 
;Task:
Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
 
If a number is 10, stop the loop after printing it, and do not generate any further numbers.
 
Otherwise, generate and print a second random number before restarting the loop.
 
If the number 10 is never generated as the first number in a loop, loop forever.
 
 
;Related tasks:
*   [[Loop over multiple arrays simultaneously]]
*   [[Loops/Break]]
*   [[Loops/Continue]]
*   [[Loops/Do-while]]
*   [[Loops/Downward for]]
*   [[Loops/For]]
*   [[Loops/For with a specified step]]
*   [[Loops/Foreach]]
*   [[Loops/Increment loop index within loop body]]
*   [[Loops/Infinite]]
*   [[Loops/N plus one half]]
*   [[Loops/Nested]]
*   [[Loops/While]]
*   [[Loops/with multiple ranges]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">L
V a = random:(20)
print(a)
I a == 10
L.break
V b = random:(20)
print(b)</syntaxhighlight>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Loops Break 15/02/2017
LOOPBREA CSECT
USING LOOPBREA,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
LOOP MVC PG,=CL80' ' clean buffer
LA R8,PG ipg=0
BAL R14,RANDINT call randint
C R6,=F'10' if k=10 then leave
BE ENDLOOP <-- loop break
BAL R14,RANDINT call randint
XPRNT PG,L'PG print buffer
B LOOP loop forever
ENDLOOP XPRNT PG,L'PG print buffer
L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
RANDINT L R5,RANDSEED randint
M R4,=F'397204091' "
D R4,=X'7FFFFFFF' "
ST R4,RANDSEED "
LR R5,R4 "
SR R4,R4 "
D R4,=F'20' "
LR R6,R4 k=randint(20)
XDECO R6,XDEC edit k
MVC 0(4,R8),XDEC+8 output k
LA R8,4(R8) ipg=ipg+4
BR R14 return
RANDSEED DC F'39710831' seed
PG DS CL80 buffer
XDEC DS CL12
YREGS
END LOOPBREA</syntaxhighlight>
{{out}}
<pre>
2 3
9 10
14 5
18 16
5 0
1 3
7 17
19 8
17 12
10
</pre>
 
=={{header|6502 Assembly}}==
Code is called as a subroutine (i.e. JSR LoopBreakSub). Specific OS/hardware routines for generating random numbers and printing are left unimplemented.
<syntaxhighlight lang="6502asm">LoopBreakSub: PHA ;push accumulator onto stack
 
 
BreakLoop: JSR GenerateRandomNum ;routine not implemented
;generates random number and puts in memory location RandomNumber
 
LDA RandomNumber
JSR DisplayAccumulator ;routine not implemented
CMP #10
BEQ Break
JSR GenerateRandomNum
LDA RandomNumber
JSR DisplayAccumulator
JMP BreakLoop
 
Break: PLA ;restore accumulator from stack
RTS ;return from subroutine</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopbreak64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndLoop: .asciz "loop break with value : \n"
szMessResult: .asciz "Resultat = @ \n" // message result
 
.align 4
qGraine: .quad 12345678
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
1: // begin loop
mov x4,20
2:
mov x0,19
bl genereraleas // generate number
cmp x0,10 // compar value
beq 3f // break if equal
ldr x1,qAdrsZoneConv // display value
bl conversion10 // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at third @ character
bl affichageMess // display message final
subs x4,x4,1 // decrement counter
bgt 2b // loop if greather
b 1b // begin loop one
3:
mov x2,x0 // save value
ldr x0,qAdrszMessEndLoop
bl affichageMess // display message
mov x0,x2
ldr x1,qAdrsZoneConv
bl conversion10 // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at third @ character
bl affichageMess // display message
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
qAdrszMessEndLoop: .quad szMessEndLoop
/***************************************************/
/* Generation random number */
/***************************************************/
/* x0 contains limit */
genereraleas:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr x3,qAdrqGraine // load graine
ldr x2,[x3]
lsr x1,x2,17 // see xorshift on wikipedia
eor x2,x2,x1
lsl x1,x2,31
eor x2,x2,x1
lsr x1,x2,8
eor x1,x2,x1
str x1,[x3] // save graine for the next call
udiv x1,x2,x0 // divide by value maxi
msub x0,x1,x0,x2 // résult = remainder
100: // end function
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************************/
qAdrqGraine: .quad qGraine
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{output}}
<pre>
Resultat = 1
Resultat = 8
Resultat = 11
Resultat = 11
Resultat = 5
Resultat = 3
Resultat = 5
Resultat = 12
Resultat = 18
Resultat = 14
loop break with value :
Resultat = 10
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE v
 
PrintE("Before loop")
DO
v=Rand(20)
PrintBE(v)
IF v=10 THEN
EXIT
FI
OD
PrintE("After loop")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Break.png Screenshot from Atari 8-bit computer]
<pre>
Before loop
2
6
3
4
11
17
5
17
10
After loop
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
 
procedure Test_Loop_Break is
type Value_Type is range 10..2019;
package Random_Values is new Ada.Numerics.Discrete_Random (Value_Type);
use Random_Values;
Line 19 ⟶ 274:
Put_Line (Value_Type'Image (B));
end loop;
end Test_Loop_Break;</langsyntaxhighlight>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">integer
main(void)
{
integer a, b;
 
while (1) {
a = drand(19);
o_integer(a);
o_byte('\n');
if (a == 10) {
break;
}
 
b = drand(19);
o_integer(b);
o_byte('\n');
}
 
return 0;
}</syntaxhighlight>
 
=={{header|ALGOL 60}}==
{{works with|ALGOL 60|OS/360}}
<syntaxhighlight lang="algol60">'BEGIN' 'COMMENT' Loops/Break - ALGOL60 - 18/06/2018;
'INTEGER' SEED;
'INTEGER' 'PROCEDURE' RANDOM(N);
'VALUE' N; 'INTEGER' N;
'BEGIN'
SEED:=(SEED*19157+12347) '/' 21647;
RANDOM:=SEED-(SEED '/' N)*N+1
'END' RANDOM;
'INTEGER' I,J,K;
SYSACT(1,6,120);SYSACT(1,8,60);SYSACT(1,12,1);'COMMENT' open print;
SEED:=31567;
J:=0;
'FOR' I:=1, I+1 'WHILE' I 'LESS' 100 'DO' 'BEGIN'
J:=J+1;
K:=RANDOM(20);
OUTINTEGER(1,K);
'IF' J=8 'THEN' 'BEGIN'
SYSACT(1,14,1); 'COMMENT' skip line;
J:=0
'END';
'IF' K=10 'THEN' 'GOTO' LAB
'END';
LAB:
SYSACT(1,14,1); 'COMMENT' skip line;
'END'</syntaxhighlight>
{{out}}
<pre>
+17 +4 +20 +3 +16 +5 +1 +17
+11 +2 +12 +5 +7 +6 +10
</pre>
 
=={{header|ALGOL 68}}==
{{trans|C|Note: This specimen retains the original C coding style. }}
{{works with|ALGOL 68|Standard - no extensions to language used}}
{{wont work with|ALGOL 68G|Any - in a68G next random takes no seed argument}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
<syntaxhighlight lang="algol68">main: (
INT a, b;
INT seed := 4; # chosen by a fair dice roll, guaranteed to be random c.f. http://xkcd.com/221/ #
# first random; #
WHILE
a := ENTIER (next random(seed) * 20);
print((a));
# WHILE # NOT (a = 10) DO
b := ENTIER (next random(seed) * 20);
print((b, new line))
OD;
print(new line)
)</syntaxhighlight>
{{out}}
<pre style="height:25ex;overflow:scroll">
+13 +6
+1 +8
+13 +2
+1 +12
+0 +12
+14 +8
+9 +2
+19 +13
+0 +4
+8 +14
+17 +7
+11 +9
+7 +8
+2 +1
+11 +2
+13 +18
+3 +7
+11 +17
+4 +13
+16 +12
+19 +17
+9 +7
+8 +5
+4 +8
+7 +5
+0 +18
+8 +13
+7 +4
+10
</pre>
 
=={{header|Amazing Hopper}}==
<p>Flavour "Jambo"</p>
<syntaxhighlight lang="c">
#include <jambo.h>
 
Main
Loop
Break if ' Int rand(20) ---show--- Is equal to (10) '
Printnl ( "--", Int rand(20) )
Back
Print '"\nEnd of Loop\n" '
End
 
</syntaxhighlight>
<p>Assembler Hopper version of this program:</p>
<syntaxhighlight lang="amazing hopper">
main:
____CODE_JUMP____997416047:,
;{20};rand;int;show;eqto(10);jt(____CODE_JUMP____803885359)
 
{"--"};{20};rand;int;{"\n"}print;
,jmp(____CODE_JUMP____997416047),____CODE_JUMP____803885359:,
{"\nEnd of Loop\n"};print;
emptystack?do{{0}};return
</syntaxhighlight>
{{out}}
<pre>
xxxx@debian:~/Proy$ hopper3 jm/rand.jambo
11--19
4--4
1--9
0--13
19--18
12--6
10
End of Loop
xxxx@debian:~/Proy$ hopper3 jm/rand.jambo
19--10
10
End of Loop
xxxx@debian:~/Proy$ hopper3 jm/rand.jambo
10
End of Loop
xxxx@debian:~/Proy$ hopper3 jm/rand.jambo
0--14
7--1
18--11
15--15
17--9
7--1
10
End of Loop
xxxx@debian:~/Proy$ hopper3 jm/rand.jambo
13--0
17--12
16--2
19--14
2--6
19--10
10
End of Loop
xxxx@debian:~/Proy$
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">repeat
set a to random number from 0 to 19
if a is 10 then
log a
exit repeat
end if
set b to random number from 0 to 19
log a & b
end repeat</syntaxhighlight>
 
 
{{out}}
<pre style="height:25ex;overflow:scroll">(*12, 6*)
(*7, 8*)
(*17, 4*)
(*7, 2*)
(*0, 5*)
(*6, 3*)
(*5, 5*)
(*3, 14*)
(*7, 7*)
(*3, 11*)
(*5, 16*)
(*18, 2*)
(*5, 2*)
(*15, 17*)
(*16, 10*)
(*4, 18*)
(*8, 5*)
(*4, 15*)
(*11, 14*)
(*7, 2*)
(*1, 7*)
(*7, 7*)
(*4, 9*)
(*12, 17*)
(*8, 16*)
(*9, 1*)
(*16, 15*)
(*8, 2*)
(*9, 6*)
(*13, 6*)
(*17, 0*)
(*17, 18*)
(*4, 7*)
(*8, 10*)
(*11, 0*)
(*14, 17*)
(*9, 8*)
(*2, 17*)
(*1, 5*)
(*4, 5*)
(*5, 2*)
(*10*)</pre>
 
=={{header|Arc}}==
<syntaxhighlight lang="arc">(point break
(while t
(let x (rand 20)
(prn "a: " x)
(if (is x 10)
(break)))
(prn "b: " (rand 20))))</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program loopbreak.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndLoop: .asciz "loop break with value : \n"
szMessResult: .ascii "Resultat = " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
.align 4
iGraine: .int 123456
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
push {fp,lr} @ saves 2 registers
1: @ begin loop
mov r4,#20
2:
mov r0,#19
bl genereraleas @ generate number
cmp r0,#10 @ compar value
beq 3f @ break if equal
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
subs r4,#1 @ decrement counter
bgt 2b @ loop if greather
b 1b @ begin loop one
3:
mov r2,r0 @ save value
ldr r0,iAdrszMessEndLoop
bl affichageMess @ display message
mov r0,r2
ldr r1,iAdrsMessValeur
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
 
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
iAdrszMessEndLoop: .int szMessEndLoop
/******************************************************************/
/* 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 */
 
/***************************************************/
/* Generation random number */
/***************************************************/
/* r0 contains limit */
genereraleas:
push {r1-r4,lr} @ save registers
ldr r4,iAdriGraine
ldr r2,[r4]
ldr r3,iNbDep1
mul r2,r3,r2
ldr r3,iNbDep1
add r2,r2,r3
str r2,[r4] @ maj de la graine pour l appel suivant
 
mov r1,r0 @ divisor
mov r0,r2 @ dividende
bl division
mov r0,r3 @ résult = remainder
100: @ end function
pop {r1-r4,lr} @ restaur registers
bx lr @ return
/********************************************************************/
iAdriGraine: .int iGraine
iNbDep1: .int 0x343FD
iNbDep2: .int 0x269EC3
/***************************************************/
/* 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
 
 
 
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">while ø [
a: random 0 19
prints [a ""]
if a=10 -> break
 
b: random 0 19
print b
]
print ""</syntaxhighlight>
 
{{out}}
 
<pre>11 1
11 16
19 14
17 0
18 11
9 9
1 15
5 5
1 16
7 10
10 </pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Loop
<lang AutoHotkey>Loop
{
Random, var, 0, 19
Line 30 ⟶ 737:
output = %output%`n%var%
}
MsgBox % output</langsyntaxhighlight>
 
=={{header|Avail}}==
<syntaxhighlight lang="avail">rng ::= a pRNG;
checked : [0..19];
Do [
checked : = rng's next [0..19];
Print: “checked”;
] while checked ≠ 10 alternate with [
Print: " " ++ “rng's next [0..19]” ++ "\n";
];</syntaxhighlight>
 
This demonstrates two interesting Avail features: the ''alternate with'' loop structures, which provide two separate code blocks that are run with a check in between, and the random number generator's ability to pick an item from the ranger of a given number type (<code>[0..19]</code> is an expression generating a ''type'' whose values are integers in the range 0-19 inclusive).
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">BEGIN {
srand() # randomize the RNG
for (;;) {
print n = int(rand() * 20)
if (n == 10)
break
print int(rand() * 20)
}
}</syntaxhighlight>
 
=={{header|Axe}}==
Because Axe only supports breaking out of loops as end conditions, the behavior must be simulated using a return statement. Note, however, that this will exit the current call context, not the necessarily just the current loop.
 
<syntaxhighlight lang="axe">While 1
rand^20→A
Disp A▶Dec
ReturnIf A=10
rand^20→B
Disp B▶Dec,i
End</syntaxhighlight>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic">FOR I = 0 TO 1 STEP 0 : N = INT(RND(1) * 20) : PRINT " "N; : IF N <> 10 THEN ? ","INT(RND(1) * 20); : NEXT</syntaxhighlight>
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">
REPEAT
number = RANDOM(20)
PRINT "first " ,number
IF number = 10 THEN
BREAK
ENDIF
PRINT "second ",RANDOM(20)
UNTIL FALSE</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">do
i = int(rand * 19)
print i; " ";
if i = 10 then exit do
i = int(rand * 19)
print i; " ";
until false
print
end</syntaxhighlight>
 
==={{header|bootBASIC}}===
In bootBASIC, the rnd statement returns an unsigned integer between 0 and 255. 255 divided by 19 gives us 13 without the fraction part, so 13 is the number to divide the random number by to get a range of 0 to 19. All division is integer division.
<syntaxhighlight lang="BASIC">
10 a=rnd/13
20 print a ;
30 if a-10 goto 50
40 goto 100
50 a=rnd/13
55 print ", ";
60 print a
70 goto 10
100 print
</syntaxhighlight>
{{out}}
<pre>
13, 19
11, 14
18, 4
17, 0
12, 15
0, 13
7, 19
2, 7
1, 3
6, 18
13, 6
9, 10
4, 7
15, 7
10
</pre>
 
==={{header|Commodore BASIC}}===
In Commodore BASIC, the function RND() generates a floating point number from 0.0 to 1.0 (exclusive).
<syntaxhighlight lang="commodorebasic">10 X = RND(-TI) : REM SEED RN GENERATOR
20 A = INT(RND(1)*20)
30 PRINT A
40 IF A = 10 THEN 80
50 B = INT(RND(1)*20)
60 PRINT B
70 GOTO 20
80 END</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 RANDOMIZE
110 DO
120 LET A=RND(20)+1
130 PRINT A,
140 IF A=10 THEN EXIT DO
150 PRINT RND(20)+1
160 LOOP</syntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang="qbasic">do
a = int(rnd * 20)
print a
Line 40 ⟶ 858:
b = int(rnd * 20)
print b
loop</langsyntaxhighlight>
 
 
==={{header|True BASIC}}===
<syntaxhighlight lang="basic">RANDOMIZE
 
DO
LET i = INT(RND * 19)
PRINT i; " ";
IF i = 10 THEN
EXIT DO
END IF
LET i = INT(RND * 19)
PRINT i; " ";
LOOP
PRINT
END</syntaxhighlight>
 
 
==={{header|uBasic/4tH}}===
In uBasic/4tH '''UNTIL''' ''<cond>'' is equivalent to '''IF''' ''<cond>'' '''THEN BREAK'''. You can add as many '''UNTIL''' and '''WHILE''' as required in '''FOR..NEXT''' or '''DO..LOOP''' loops.
<syntaxhighlight lang="qbasic">Do
n = Rnd(20)
Print n
Until n=10
Print Rnd(20)
Loop</syntaxhighlight>
==={{header|ZX Spectrum Basic}}===
On the ZX Spectrum, for loops must be terminated through the NEXT statement, otherwise a memory leak will occur. To terminate a loop prematurely, set the loop counter to the last iterative value and jump to the NEXT statement:
 
<syntaxhighlight lang="zxbasic">10 FOR l = 1 TO 20
20 IF l = 10 THEN LET l = 20: GO TO 40: REM terminate the loop
30 PRINT l
40 NEXT l
50 STOP</syntaxhighlight>
 
The correct solution:
 
<syntaxhighlight lang="zxbasic">10 LET a = INT (RND * 20)
20 PRINT a
30 IF a = 10 THEN STOP
40 PRINT INT (RND * 20)
50 GO TO 10</syntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">@echo off
:loop
set /a N=%RANDOM% %% 20
echo %N%
if %N%==10 exit /b
set /a N=%RANDOM% %% 20
echo %N%
goto loop</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> REPEAT
num% = RND(20)-1
PRINT num%
IF num%=10 THEN EXIT REPEAT
PRINT RND(20)-1
UNTIL FALSE</syntaxhighlight>
 
=={{header|bc}}==
<syntaxhighlight lang="bc">s = 1 /* seed of the random number generator */
scale = 0
 
/* Random number from 0 to 20. */
define r() {
auto a
while (1) {
/* Formula (from POSIX) for random numbers of low quality. */
s = (s * 1103515245 + 12345) % 4294967296
a = s / 65536 /* a in [0, 65536) */
if (a >= 16) break /* want a >= 65536 % 20 */
}
return (a % 20)
}
 
 
while (1) {
n = r()
n /* print 1st number */
if (n == 10) break
r() /* print 2nd number */
}
quit</syntaxhighlight>
 
=={{header|Befunge}}==
<syntaxhighlight lang="befunge">
>60v *2\<
>?>\1-:|
1+ $
>^ 7
v.:%++67<
>55+-#v_@
>60v *2\<
>?>\1-:|
1+ $
>^ 7
^ .%++67<
</syntaxhighlight>
 
=={{header|C}}==
<lang c>#include <stdlib.h>
#include <time.h>
#include <stdio.h>
 
<syntaxhighlight lang="c">
int main() {
int a, b;main(){
time_t t;
int a, b;
srand((unsigned)time(&t));
for(;;){
a = rand() % 20;
printf("%d\n", a);
if(a == 10)
break;
b = rand() % 20;
printf("%d\n", b);
}
return 0;
}</syntaxhighlight>
Output (example):
<pre>
12
18
2
8
10
18
9
9
4
10
</pre>
 
srand(time(NULL));
while (1) {
a = rand() % 20; /* not exactly uniformly distributed, but doesn't matter */
printf("%d\n", a);
if (a == 10) break;
b = rand() % 20; /* not exactly uniformly distributed, but doesn't matter */
printf("%d\n", b);
}
return 0;
}</lang>
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">class Program
{
class Program
static void Main(string[] args)
{
Random random = new Random();
staticwhile void Main(string[] argstrue)
{
Randomint randoma = new Randomrandom.Next(20);
while Console.WriteLine(truea);
{if (a == 10)
int a = random.Next(20)break;
int b = Consolerandom.WriteLineNext(a20);
if Console.WriteLine(a == 10b);
break;
int b = random.Next(20);
Console.WriteLine(b);
}
Console.ReadLine();
}
Console.ReadLine();
}
}</syntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <ctime>
#include <cstdlib>
 
int main(){
srand(time(NULL)); // randomize seed
while(true){
const int a = rand() % 20; // biased towards lower numbers if RANDMAX % 20 > 0
std::cout << a << std::endl;
if(a == 10)
break;
const int b = rand() % 20;
std::cout << b << std::endl;
}
return 0;
}</syntaxhighlight>
 
=={{header|Chapel}}==
<syntaxhighlight lang="chapel">use Random;
 
var r = new RandomStream();
while true {
var a = floor(r.getNext() * 20):int;
writeln(a);
if a == 10 then break;
var b = floor(r.getNext() * 20):int;
writeln(b);
}
delete r;</syntaxhighlight>
 
}
</lang>
=={{header|Chef}}==
"Liquify" is now depreciated in favor of "Liquefy", but my interpreter/compiler ([http://search.cpan.org/~smueller/Acme-Chef/ Acme::Chef]) works only with "Liquify" so that's how I'm leaving it. At least it'll work no matter which version you use.
<div style='width:full;overflow:scroll'>
<langsyntaxhighlight Cheflang="chef">Healthy Vita-Sauce Loop - Broken.
 
Makes a whole lot of sauce for two people.
Line 145 ⟶ 1,103:
Pour contents of the 1st mixing bowl into the 1st baking dish.
 
Serves 2.</langsyntaxhighlight>
</div>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(loop [[a b & more] (repeatedly #(rand-int 20))]
(println a)
(when-not (= 10 a)
(println b)
(recur more)))</langsyntaxhighlight>
 
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Random-Nums.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num PIC Z9.
 
PROCEDURE DIVISION.
Main.
PERFORM FOREVER
PERFORM Generate-And-Display-Num
 
IF Num = 10
EXIT PERFORM
ELSE
PERFORM Generate-And-Display-Num
END-IF
END-PERFORM
 
GOBACK
.
 
Generate-And-Display-Num.
COMPUTE Num = FUNCTION REM(FUNCTION RANDOM * 100, 20)
DISPLAY Num
.</syntaxhighlight>
 
=={{header|CoffeeScript}}==
We can use print from the Rhino JavaScript shell as in the JavaScript example or console.log, with a result like this:
<syntaxhighlight lang="coffeescript">
loop
print a = Math.random() * 20 // 1
break if a == 10
print Math.random() * 20 // 1
</syntaxhighlight>
 
=={{header|ColdFusion}}==
<syntaxhighlight lang="cfm">
<Cfset randNum = 0>
<cfloop condition="randNum neq 10">
<Cfset randNum = RandRange(0, 19)>
<Cfoutput>#randNum#</Cfoutput>
<Cfif randNum eq 10><cfbreak></Cfif>
<Cfoutput>#RandRange(0, 19)#</Cfoutput>
<Br>
</cfloop>
</syntaxhighlight>
{{out}}
My first two test outputs (I swear this is true)
<pre style="height:25ex;overflow:scroll">
6 0
9 6
12 3
6 0
14 10
19 12
18 14
19 8
3 2
19 1
11 12
16 9
11 15
3 19
13 8
6 4
4 4
13 17
16 9
5 12
12 6
4 14
1 10
3 7
11 15
11 8
0 16
16 14
8 14
11 10
8 8
16 11
4 7
19 10
8 2
15 11
18 10
1 2
18 9
4 9
6 6
11 8
14 6
17 15
13 2
2 0
2 17
8 17
18 13
11 5
15 18
17 8
15 3
7 17
7 13
15 14
11 9
10
</pre>
<pre>
10
</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(loop for a = (random 20)
(setq a do (randomprint 20)a)
until (print= a 10)
do (print (random 20)))</syntaxhighlight>
(if (= a 10)
(return))
(setq b (random 20))
(print b))</lang>
 
=={{header|D}}= Using DO ===
<syntaxhighlight lang="lisp">
{{works with|Tango}}
(do ((a (random 20) (random 20))) ; Initialize to rand and set new rand on every loop
((= a 10) (write a)) ; Break condition and last step
(format t "~a~3T~a~%" a (random 20))) ; On every loop print formated `a' and rand `b'
</syntaxhighlight>
 
{{out}}
Using Mersenne twister;
<pre>
19 7
8 16
17 10
19 12
7 16
5 19
16 1
8 8
3 18
3 5
3 3
9 7
1 15
1 10
14 10
2 4
13 6
10
</pre>
 
=={{header|D}}==
<lang D>import tango.io.Stdout;
<syntaxhighlight lang="d">import tangostd.mathstdio, std.random.Twister;
 
void main() {
aliaswhile Twister.instance(true) r;{
int r = uniform(0, 20);
uint x;
write(r, " ");
 
while if (~1)r {== 10)
x = r.natural(20) break;
Stdout write(xuniform(0, 20), (" ");
if (x == 10) break;
Stdout (r.natural(20)).newline;
}
}</langsyntaxhighlight>
{{out}}
<pre>2 4 9 5 3 7 4 4 14 14 3 7 13 8 13 6 10 </pre>
 
=={{header|dc}}==
{{trans|bc}}
<syntaxhighlight lang="dc">1 ss [s = seed of the random number generator]sz
0k [scale = 0]sz
 
[Function r: Push a random number from 0 to 20.]sz
[
[2Q]SA
[
[Formula (from POSIX) for random numbers of low quality.]sz
ls 1103515245 * 12345 + 4294967296 % d ss [Compute next s]sz
65536 / [it = s / 65536]sz
d 16 !>A [Break loop if 16 <= it]sz
sz 0 0 =B [Forget it, continue loop]sz
]SB 0 0 =B
20 % [Push it % 20]sz
LA sz LB sz [Restore A, B]sz
]sr
 
 
[2Q]sA
[
0 0 =r p [Print 1st number.]sz
10 =A [Break if 10 == it.]sz
0 0 =r p sz [Print 2nd number.]sz
0 0 =B [Continue loop.]sz
]sB 0 0 =B</syntaxhighlight>
 
=={{header|Delphi}}==
 
<syntaxhighlight lang="delphi">program Project5;
 
{$APPTYPE CONSOLE}
 
var
num:Integer;
begin
Randomize;
while true do
begin
num:=Random(20);
Writeln(num);
if num=10 then break;
end;
end.
 
</syntaxhighlight>
 
=={{header|DWScript}}==
 
<syntaxhighlight lang="delphi">
while True do begin
var num := RandomInt(20);
PrintLn(num);
if num=10 then Break;
end;</syntaxhighlight>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">while (true) {
def a := entropy.nextInt(20)
print(a)
Line 193 ⟶ 1,344:
}
println(" ", entropy.nextInt(20))
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
repeat
a = randint 20
print a
until a = 10
print randint 20
.
</syntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
example
-- Eiffel example code
local
n: INTEGER
r: RANDOMIZER
do
from
create r
n := r.random_integer_in_range (0 |..| 19)
until
n = 10
loop
n := r.random_integer_in_range (0 |..| 19)
end
end
</syntaxhighlight>
{{out}}
The output is superfluous and unneeded to read and understand what the Eiffel code is doing.
The test code is sufficient to prove that it works.
Uses randomizer library located at: https://github.com/ljr1981/randomizer
 
=={{header|Ela}}==
 
This implementation uses .NET Framework Math.Randomize function.
Current ticks multiplied by an iteration index are used as a seed.
As a result, an output looks almost truly random:
 
<syntaxhighlight lang="ela">open datetime random monad io
loop = loop' 1
where loop' n t = do
dt <- datetime.now
seed <- return <| toInt <| (ticks <| dt) * n
r <- return $ rnd seed 0 19
putStrLn (show r)
if r <> t then loop' (n + 1) t else return ()
 
 
loop 10 ::: IO</syntaxhighlight>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<syntaxhighlight lang="elixir">defmodule Loops do
def break, do: break(random)
defp break(10), do: IO.puts 10
defp break(r) do
IO.puts "#{r},\t#{random}"
break(random)
end
defp random, do: Enum.random(0..19)
end
 
Loops.break</syntaxhighlight>
 
{{out}}
<pre>
13, 7
12, 7
2, 16
3, 19
17, 10
5, 17
14, 0
7, 6
5, 19
5, 12
4, 2
8, 14
1, 17
13, 5
10
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun wait_10 ()
(catch 'loop-break
(while 't
(let ((math (random 19)))
(if (= math 10)
(progn (message "Found value: %d" math)
(throw 'loop-break math))
(message "current number is: %d" math) ) ) ) ) )
 
(wait_10)</syntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
for ever
int a = random(20)
write(a)
if a == 10 do break end
writeLine("," + random(20))
end
writeLine()
</syntaxhighlight>
{{out}}
<pre>
19,14
10
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">%% Implemented by Arjun Sunel
-module(forever).
-export([main/0, for/0]).
main() ->
for().
for() ->
K = random:uniform(19),
io:fwrite( "~p ", [K] ),
if K==10 ->
ok;
true ->
M = random:uniform(19),
io:format("~p~n",[M]),
for()
end.
</syntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
LOOP
A=INT(RND(1)*20)
PRINT(A)
IF A=10 THEN EXIT LOOP END IF !EXIT FOR works the same inside FOR loops
PRINT(INT(RND(1)*20))
END LOOP
</syntaxhighlight>
The <code>RND(X)</code> function returns a random integer from 0 to 1. X is a dummy argument.
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">integer i
while 1 do
i = rand(20) - 1
printf(1, "%g ", {i})
if i = 10 then
exit
end if
printf(1, "%g ", {rand(20)-1})
end while</syntaxhighlight>
The <code>rand()</code> function returns a random integer from 1 to the integer provided.
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Loops/Break. Nigel Galloway: February 21st., 2022
let n=System.Random()
let rec fN g=printf "%d " g; if g <> 10 then fN(n.Next(20))
fN(n.Next(20))
</syntaxhighlight>
 
=={{header|Factor}}==
Using <code>with-return</code>:
<syntaxhighlight lang="factor">[
[ 20 random [ . ] [ 10 = [ return ] when ] bi 20 random . t ] loop
] with-return</syntaxhighlight>
 
Idiomatic Factor:
<syntaxhighlight lang="factor">[ 20 random [ . ] [ 10 = not ] bi dup [ 20 random . ] when ] loop</syntaxhighlight>
 
=={{header|Fantom}}==
 
<syntaxhighlight lang="fantom">
class ForBreak
{
public static Void main ()
{
while (true)
{
a := Int.random(0..19)
echo (a)
if (a == 10) break
echo (Int.random(0..19))
}
}
}
</syntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">include random.fs
 
: main
Line 209 ⟶ 1,553:
10 = if leave then
i random .
loop ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Example
implicit none
 
Line 229 ⟶ 1,573:
end do
 
end program Example</langsyntaxhighlight>
 
{{works with|Fortran|77 and later}}
<syntaxhighlight lang="fortran"> PROGRAM LOOPBREAK
INTEGER I, RNDINT
 
C It doesn't matter what number you put here.
CALL SDRAND(123)
 
C Because FORTRAN 77 semantically lacks many loop structures, we
C have to use GOTO statements to do the same thing.
10 CONTINUE
C Print a random number.
I = RNDINT(0, 19)
WRITE (*,*) I
 
C If the random number is ten, break (i.e. skip to after the end
C of the "loop").
IF (I .EQ. 10) GOTO 20
 
C Otherwise, print a second random number.
I = RNDINT(0, 19)
WRITE (*,*) I
 
C This is the end of our "loop," meaning we jump back to the
C beginning again.
GOTO 10
 
20 CONTINUE
 
STOP
END
 
C FORTRAN 77 does not come with a random number generator, but it
C is easy enough to type "fortran 77 random number generator" into your
C preferred search engine and to copy and paste what you find. The
C following code is a slightly-modified version of:
C
C http://www.tat.physik.uni-tuebingen.de/
C ~kley/lehre/ftn77/tutorial/subprograms.html
SUBROUTINE SDRAND (IRSEED)
COMMON /SEED/ UTSEED, IRFRST
UTSEED = IRSEED
IRFRST = 0
RETURN
END
INTEGER FUNCTION RNDINT (IFROM, ITO)
INTEGER IFROM, ITO
PARAMETER (MPLIER=16807, MODLUS=2147483647, &
& MOBYMP=127773, MOMDMP=2836)
COMMON /SEED/ UTSEED, IRFRST
INTEGER HVLUE, LVLUE, TESTV, NEXTN
SAVE NEXTN
IF (IRFRST .EQ. 0) THEN
NEXTN = UTSEED
IRFRST = 1
ENDIF
HVLUE = NEXTN / MOBYMP
LVLUE = MOD(NEXTN, MOBYMP)
TESTV = MPLIER*LVLUE - MOMDMP*HVLUE
IF (TESTV .GT. 0) THEN
NEXTN = TESTV
ELSE
NEXTN = TESTV + MODLUS
ENDIF
IF (NEXTN .GE. 0) THEN
RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + IFROM
ELSE
RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + ITO + 1
ENDIF
RETURN
END</syntaxhighlight>
 
{{works with|Fortran|66 and earlier}}
Anyone who attempts to produce random numbers via a computation is already in a state of sin, so, one might as well be hung as a goat rather than as a lamb. Here is a version using the RANDU generator, in the style of Fortran 66 as offered by the IBM1130. No logical-if statements and reliance on implicit type declarations. Sixteen-bit integers result. The standard advice is to start IX off as an odd number. Note that RANDU does ''not'' update IX (the "seed"); the caller must do so. Since integer overflow producing negative numbers is undone by adding 32768 (trusting that the compiler will not attempt to combine constants, thus + 32767 + 1) in the absence of an AND operation, possible values for IY are presumably zero to 32767. Since IY is divided by 32767.0 (''not'' 32768.0 for example), the range for YFL is zero to one ''inclusive'', though further inspection shows that zero is not attained for proper starts - should IX be zero it will never change, thus the span is (0,1]; a more common arrangement is [0,1).
 
Because the upper bound ''is'' attainable, multiplying YFL by 19 and truncating the result will mean that 19 appears only as an edge event when IY = 32767. Multiplying by 20 will ensure that 19 gets its fair share along with each other integer, but, the edge event might now occasionally produce a 20. There is no MIN function available, so, explicit testing results. Rather than repeat this code with its consequent litter of labels, a helper function IR19 does the work once. These out-by-one opportunities are vexing.
 
The RANDU routine is so notorious that latter-day compilers can supply their own RANDU (using a better method), and further, disregard a user-supplied RANDU routine so it may have to be called RANDUU or some other name!
<syntaxhighlight lang="fortran">
SUBROUTINE RANDU(IX,IY,YFL)
Copied from the IBM1130 Scientific Subroutines Package (1130-CM-02X): Programmer's Manual, page 60.
CAUTION! This routine's 32-bit variant is reviled by Prof. Knuth and many others for good reason!
IY = IX*899
IF (IY) 5,6,6
5 IY = IY + 32767 + 1
6 YFL = IY
YFL = YFL/32767.
END
 
FUNCTION IR19(IX)
CALL RANDU(IX,IY,YFL)
IX = IY
I = YFL*20
IF (I - 20) 12,11,11
11 I = 19
12 IR19 = I
END
 
IX = 1
Commence the loop.
10 I = IR19(IX)
WRITE (6,11) I
11 FORMAT (I3)
IF (I - 10) 12,20,12
12 I = IR19(IX)
WRITE (6,11) I
GO TO 10
Cease.
20 CONTINUE
END
</syntaxhighlight>
Output, converted to along the line:
0 13 4 19 1 7 2 12 4 7 14 11 6 4 0 9 5 12 16 19 18 2 0 13 2 7 10
This source will compile with later compilers (possibly after adding INTEGER*2 declarations to not use larger integers), as well as earlier compilers. But the IBM1620's Fortran II ran on a decimal computer (and the compiler allowed an option to specify how many digits in a number) so the assumption of sixteen-bit two's-complement arithmetic would fail. There was once much more variety in computer design, not just always a power of two in word sizes.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim i As Integer
Randomize
Do
i = Int(Rnd * 20)
Print Using "##"; i;
Print " ";
If i = 10 Then Exit Do
i = Int(Rnd * 20)
Print Using "##"; i;
Print" ";
Loop
 
Print
Sleep</syntaxhighlight>
 
Sample output
 
{{out}}
<pre>
6 12 2 16 5 19 9 6 16 1 16 10 1 4 18 3 2 9 19 0
19 13 0 0 12 17 13 12 18 10 8 13 9 5 14 7 10
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">while true
{
a = random[0,19]
print["$a "]
if a == 10
break
 
b = random[0,19]
print["$b "]
}</syntaxhighlight>
{{out}}
<pre>
3 8 8 8 11 6 3 2 10
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
 
long num
do
num = rnd(20) - 1
NSLog(@"%ld",num)
until ( num == 10 )
 
HandleEvents</syntaxhighlight>
 
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim iRand As Integer
 
Repeat
iRand = Rnd * 20
Print iRand
Until iRand = 10
 
End</syntaxhighlight> =={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=65d2287312298a938e7e8eea8899e38b Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim byNo As Byte
 
Do
byNo = Rand(0, 19)
Print byNo;;
If byNo = 10 Then Break
byNo = Rand(0, 19)
Print byNo;;
Loop
 
End</syntaxhighlight>
Output:
<pre>
0 5 12 8 1 13 16 5 4 11 5 7 15 12 16 7 9 10 13 19 4 10 2 13 16 7 0 1 16 3 17 10 0 16 14 0 0 8 6 2 1 5 9 12 2 18 15 1 1 17 9 18 8 17 19 12 6 19 9 5 15 1 2 7 2 11 18 1 15 19 10
</pre>
 
=={{header|GAP}}==
<syntaxhighlight lang="gap">while true do
a := Random(0, 19);
Print(a);
if a = 10 then
Print("\n");
break;
fi;
a := Random(0, 19);
Print("\t", a, "\n");
od;
 
# 11 6
# 5 8
# 1 4
# 5 10
# 1 16
# 10</syntaxhighlight>
 
=={{header|GDScript}}==
{{works with|Godot|4.0.1}}
{{trans|11l}}
 
<syntaxhighlight lang="gdscript">
extends MainLoop
 
 
func _process(_delta: float) -> bool:
randomize()
 
while true:
var a: int = randi_range(0, 19)
print(a)
if a == 10:
break
var b: int = randi_range(0, 19)
print(b)
 
return true # Exit
</syntaxhighlight>
 
=={{header|GML}}==
<syntaxhighlight lang="gml">while(1)
{
a = floor(random(19))
show_message(string(a))
if(a = 10)
break
b = floor(random(19))
show_message(string(a))
}
</syntaxhighlight>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import "fmt"
import "math/rand"
import "time"
 
func main() {
rand.Seed(time.Now().UnixNano())
for {
a := rand.Intn(20)
fmt.Println(a)
if a == 10 {
break
}
b := rand.Intn(20)
fmt.Println(b)
}
}</syntaxhighlight>
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">final random = new Random()
 
while (true) {
def random1 = random.nextInt(20)
print random1
if (random1 == 10) break
print ' '
println random.nextInt(20)
}</syntaxhighlight>
 
=={{header|GW-BASIC}}==
<syntaxhighlight lang="qbasic">10 NUM = 0
20 WHILE NUM <> 10
30 NUM = INT(RND * 20)
40 PRINT NUM
50 WEND</syntaxhighlight>
 
=={{header|Harbour}}==
<syntaxhighlight lang="visualfoxpro">PROCEDURE Loop()
 
LOCAL n
 
DO WHILE .T.
? n := hb_RandomInt( 0, 19 )
IF n == 10
EXIT
ENDIF
? hb_RandomInt( 0, 19 )
ENDDO
 
RETURN</syntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad
import System.Random
 
Line 240 ⟶ 1,885:
unless (r==k) $ do
print =<< randomRIO (0,n)
loopBreak n k</langsyntaxhighlight>
Use:
<syntaxhighlight lang ="haskell">loopBreak 19 10</langsyntaxhighlight>
 
=={{header|Haxe}}==
<syntaxhighlight lang="haxe">class Program {
static public function main():Void {
while(true) {
var a = Std.random(20);
Sys.println(a);
if (a == 10)
break;
var b = Std.random(20);
Sys.println(b);
}
}
}</syntaxhighlight>
 
=={{header|hexiscript}}==
<syntaxhighlight lang="hexiscript">while true
let r rand 20
println r
if r = 10
break
endif
println rand 20
endwhile</syntaxhighlight>
 
=={{header|HicEst}}==
<syntaxhighlight lang="hicest">1 DO i = 1, 1E20 ! "forever"
a = INT( RAN(10, 10) )
WRITE(name) a
IF( a == 10) GOTO 10
b = INT( RAN(10, 10) )
WRITE(name) b
ENDDO
10
END</syntaxhighlight>
 
=={{header|HolyC}}==
 
<syntaxhighlight lang="holyc">U16 a, b;
while (1) {
a = RandU16 % 20;
Print("%d\n", a);
 
if (a == 10) break;
 
b = RandU16 % 20;
Print("%d\n", b);
}
</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">procedure main()
while 10 ~= writes(?20-1) do write(", ",?20-1)
end</syntaxhighlight>
Notes:
* For any positive integer i, ?i produces a value j where 1 <= j <= i
* Although this can be written with a break (e.g. repeat expression & break), there is no need to actually use one. (And it's ugly).
* Programmers new to Icon/Unicon need to understand that just about everything returns values including comparison operators, I/O functions like write/writes.
* This program will perform similarly but not identically under Icon and Unicon because the random operator ?i behaves differently. While both produce pseudo-random numbers a different generator is used. Also, the sequence produced by Icon begins with the same seed value and is repeatable whereas the sequence produced by Unicon does not. One way to force Icon to use different random sequences on each call would be to add the line <syntaxhighlight lang="icon">&random := integer(map("smhSMH","Hh:Mm:Ss",&clock))</syntaxhighlight> at the start of the <tt>main</tt> procedure to set the random number seed based on the time of day.
 
=={{Header|Insitux}}==
 
<syntaxhighlight lang="insitux">
(while true
(print (let x (rand-int 0 20)))
(when (= x 10) (break)))
</syntaxhighlight>
 
=={{header|Io}}==
<syntaxhighlight lang="io">loop(
a := Random value(0,20) floor
write(a)
if( a == 10, writeln ; break)
b := Random value(0,20) floor
writeln(" ",b)
)</syntaxhighlight>
 
=={{header|J}}==
In recent versions of J, [[j:Vocabulary/zcapco|Z:]] can be used to provide early termination from a [[j:Vocabulary/fcap|fold]]. For example:
<lang j>loopexample=: verb define
 
while. 1 do.
<syntaxhighlight lang=J> ]F.(( _2 Z: 10&= [ echo)@(?@20))''
smoutput n=. ?20
15
if. 10=n do.return.end.
6
smoutput ?20
5
10
 
]F.(( _2 Z: 10&= [ echo)@(?@20))''
14
9
3
8
19
14
5
13
8
1
19
2
10
 
</syntaxhighlight>
 
But other mechanisms are also supported:
 
<syntaxhighlight lang="j">loopexample=: {{
while. do.
echo k=. ?20
if. 10=k do. return. end.
echo ?20
end.
}}</syntaxhighlight>
)</lang>
 
Note that <code>break.</code> or <code>goto_FOO.</code> could have been used in place of <code>return.</code>:
 
<syntaxhighlight lang="j">loopexample2=: verb define
while. do.
echo k=. ?20
if. 10=k do. break. end.
echo ?20
end.
)</syntaxhighlight>
 
<syntaxhighlight lang="j">loopexample3=: {{
while. do.
echo k=. ?20
if. 10=k do. goto_done. end.
echo ?20
end.
label_done.
}}</syntaxhighlight>
 
=={{header|Jakt}}==
The random number generation is slightly biased, but negligible for the purpose of the task.
 
<syntaxhighlight lang="jakt">
fn random(mut random_source: File = File::open_for_reading("/dev/urandom")) throws -> u64 {
mut buffer = [0u8; 4]
random_source.read(buffer)
mut result = 0u64
for byte in buffer {
result <<= 8
result += byte as! u64
}
return result
}
 
fn main() {
while true {
let n = random() % 20
println("{}", n)
if n == 10 {
break
}
 
println("{}", random() % 20)
}
}
</syntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Random;
 
Random rand = new Random();
Line 263 ⟶ 2,058:
int b = rand.nextInt(20);
System.out.println(b);
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">for (;;) {
var a = Math.floor(Math.random() * 20);
print(a);
Line 273 ⟶ 2,068:
a = Math.floor(Math.random() * 20);
print(a);
}</langsyntaxhighlight>
The <code>print()</code> function is available in the [[Rhino]] JavaScript shell.
 
 
If we step back for a moment from imperative assumptions about repetitive processes and their interruption, we may notice that there is actually no necessary connection between repetitive process and loops.
 
In a functional idiom of JavaScript, we might instead write something like:
 
<syntaxhighlight lang="javascript">(function streamTillInitialTen() {
var nFirst = Math.floor(Math.random() * 20);
console.log(nFirst);
if (nFirst === 10) return true;
console.log(
Math.floor(Math.random() * 20)
);
return streamTillInitialTen();
})();</syntaxhighlight>
 
Obtaining runs like:
 
<pre>18
10
16
10
8
0
13
3
2
14
15
17
14
7
10
8
0
2
0
2
5
16
3
16
6
7
19
0
16
9
7
11
17
10</pre>
 
Though returning a value composes better, and costs less IO traffic, than firing off side-effects from a moving thread:
 
<syntaxhighlight lang="javascript">console.log(
(function streamTillInitialTen() {
var nFirst = Math.floor(Math.random() * 20);
if (nFirst === 10) return [10];
return [
nFirst,
Math.floor(Math.random() * 20)
].concat(
streamTillInitialTen()
);
})().join('\n')
);</syntaxhighlight>
 
Sample result:
<pre>17
14
3
4
13
10
15
5
10</pre>
 
=={{header|jq}}==
 
With the functions defined below, the task can be accomplished using the following jq filter:
 
take( rand(20); . != 10 )
Here, `rand(n)` is a pseudo-random number generator, and `take(stream; cond)` will continue taking from the stream so long as the condition is satisfied. When the condition is no longer satisfied, the PRNG is immediately terminated.
 
Using the built-in `foreach` construct, the above is equivalent to:
label $done | foreach rand(20) as $n (null; $n; if . == 10 then break $done else . end)
 
'''PRNG'''
 
Currently, jq does not have a built-in random-number generator, so here we borrow one of the linear congruential generators defined at https://rosettacode.org/wiki/Linear_congruential_generator -
<syntaxhighlight lang="jq"># 15-bit integers generated using the same formula as rand()
# from the Microsoft C Runtime.
# Input: [ count, state, rand ]
def next_rand_Microsoft:
.[0] as $count | .[1] as $state
| ( (214013 * $state) + 2531011) % 2147483648 # mod 2^31
| [$count+1 , ., (. / 65536 | floor) ];
def rand_Microsoft(seed):
[0,seed]
| next_rand_Microsoft # the seed is not so random
| recurse( next_rand_Microsoft )
| .[2];
 
# Generate random integers from 0 to (n-1):
def rand(n): n * (rand_Microsoft(17) / 32768) | trunc;</syntaxhighlight>
 
'''"take"'''
 
<syntaxhighlight lang="jq">def take(s; cond):
label $done
| foreach s as $n (null; $n; if $n | cond | not then break $done else . end);</syntaxhighlight>
 
'''"count"'''
 
Since the PRNG used here is deterministic, we'll just count the number of integers generated:
<syntaxhighlight lang="jq">def count(s): reduce s as $i (0; . + 1);</syntaxhighlight>
 
'''Example'''
count(take(rand(20); . != 10))
{{out}}
12
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
while true
n = rand(0:19)
@printf "%4d" n
if n == 10
println()
break
end
n = rand(0:19)
@printf "%4d\n" n
end
</syntaxhighlight>
{{out}}
<pre>
0 11
11 7
4 19
7 19
5 2
5 17
12 5
14 18
1 10
18 14
16 0
17 1
10
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.random.Random
 
fun main() {
while (true) {
val a = Random.nextInt(20)
println(a)
if (a == 10) break
println(Random.nextInt(20))
}
}</syntaxhighlight>
 
A more compact version:
 
<syntaxhighlight lang="kotlin">fun main() {
while ((0..19).random().also { println(it) } != 10)
println((0..19).random())
}</syntaxhighlight>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def loops_break
{lambda {:n}
{if {= :n 10}
then :n -> end of loop
else :n {loops_break {round {* 20 {random}}}}}}}
-> loops_break
 
{loops_break 0}
-> 0 16 8 5 9 17 9 18 1 18 1 1 12 13 15 1 10 -> end of loop
</syntaxhighlight>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
loop {
$a = fn.randRange(20)
fn.printf(%2d, $a)
if($a === 10) {
fn.println()
con.break
}
$b = fn.randRange(20)
fn.printf(\s- %2d%n, $b)
}
</syntaxhighlight>
 
=={{header|Lang5}}==
<syntaxhighlight lang="lang5">do 20 ? int dup . 10 == if break then 20 ? int . loop</syntaxhighlight>
 
=={{header|langur}}==
<syntaxhighlight lang="langur">for {
val .i = random 0..19
write .i, " "
if .i == 10 { writeln(); break }
}</syntaxhighlight>
 
{{out}}
<pre>13 18 14 8 0 5 17 13 9 13 6 5 13 16 6 9 11 18 10</pre>
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">local(x = 0)
while(#x != 10) => {^
#x = integer_random(19,0)
#x
#x == 10 ? loop_abort
', '+integer_random(19,0)+'\r'
^}</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
The task specifies a "number".
<syntaxhighlight lang="lb">while num<>10
num=rnd(1)*20
print num
if num=10 then exit while
print rnd(1)*20
wend
</syntaxhighlight>If "integer" was meant, this code fulfils that requirement.
<syntaxhighlight lang="lb">while num<>10
num=int(rnd(1)*20)
print num
if num=10 then exit while
print int(rnd(1)*20)
wend
</syntaxhighlight>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">repeat while TRUE
n = random(20)-1
put n
if n = 10 then exit repeat
put random(20)-1
end repeat</syntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">Section Header
 
+ name := TEST_LOOP_BREAK;
Line 297 ⟶ 2,350:
'\n'.print;
}
);</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<syntaxhighlight lang="livecode">command loopForeverRandom
repeat forever
put random(20) - 1 into tRand
put tRand
if tRand is 10 then exit repeat
put random(20) - 1
end repeat
end loopForeverRandom
</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">repeat
k = math.random(19)
print(k)
if k == 10 then break end
print(math.random(19)
until false</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
We use block of module to loop. Break also can be used, but breaks nested blocks (without crossing modules/functions). Using break in second Checkit module we break three blocks.
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
M=Random(0, 19)
Print M
If M=10 then Continue ' because loop flag is false, continue act as Exit
Print Random(0, 19)
loop
}
Checkit
 
Module Checkit {
do {
do {
{
M=Random(0, 19)
Print M
If M=10 then Break
Print Random(0, 19)
loop
}
Print "no print this"
} always
Print "no print this"
} always
Print "print ok"
}
Checkit
</syntaxhighlight>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`randSeed',141592653)dnl
define(`setRand',
`define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')dnl
Line 311 ⟶ 2,414:
loopbreak')')dnl
dnl
loopbreak</langsyntaxhighlight>
 
{{out}}
Output:
<pre>
a=17
Line 321 ⟶ 2,424:
a=10
</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">r := rand( 0 .. 19 ):
do
n := r();
printf( "%d\n", n );
if n = 10 then
break
end if;
printf( "%d\n", r() );
end do:</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">While[(Print[#];#!=10)&[RandomIntger[{0,19}]],
Print[RandomInteger[{0,19}]
]</syntaxhighlight>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">/* To exit the innermost block, use return(<value>) */
 
block([n],
do (
n: random(20),
ldisp(n),
if n = 10 then return(),
n: random(20),
ldisp(n)
)
)$
 
/* To exit any level of block, use catch(...) and throw(<value>);
they are not used for catching exceptions, but for non-local
return. Use errcatch(...) for exceptions. */
 
block([n],
catch(
do (
n: random(20),
ldisp(n),
if n = 10 then throw('done),
n: random(20),
ldisp(n)
)
)
)$
 
/* There is also break(<value>, ...) in Maxima. It makes Maxima
stop the evaluation and enter a read-eval loop where one can change
variable values, then return to the function after exit; For example */
 
block([x: 1], break(), ldisp(x));
> x: 2;
> exit;
2</syntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
while true do
(
a = random 0 19
format ("A: % \n") a
if a == 10 do exit
b = random 0 19
format ("B: % \n") b
)
</syntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.6}}
<syntaxhighlight lang="min">randomize
(19 random puts 10 ==) (19 random puts!) () () linrec</syntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">СЧ 2 0 * П0
1 0 - [x] x#0 18
СЧ 2 0 * П1
БП 00 ИП0 С/П</syntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Break EXPORTS Main;
 
IMPORT IO, Fmt, Random;
Line 339 ⟶ 2,519:
END;
END;
END Break.</langsyntaxhighlight>
 
=={{header|MOO}}==
<langsyntaxhighlight lang="moo">while (1)
a = random(20) - 1;
player:tell(a);
Line 350 ⟶ 2,530:
b = random(20) - 1;
player:tell(b);
endwhile</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<syntaxhighlight lang="mumps">BREAKLOOP
NEW A,B
SET A=""
FOR Q:A=10 DO
.SET A=$RANDOM(20)
.WRITE !,A
.Q:A=10
.SET B=$RANDOM(20)
.WRITE ?6,B
KILL A,B
QUIT
;A denser version that doesn't require two tests
NEW A,B
FOR SET A=$RANDOM(20) WRITE !,A QUIT:A=10 SET B=$RANDOM(20) WRITE ?6,B
KILL A,B QUIT</syntaxhighlight>
{{out}}
<pre>USER>D BREAKLOOP^ROSETTA
5 3
9 13
3 12
9 19
16 4
11 17
18 2
4 18
10
USER>D BREAKLOOP+11^ROSETTA
6 13
15 3
0 8
8 18
7 13
15 10
15 13
10</pre>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
Loops/Break in Neko
Tectonics:
nekoc loops-break.neko
neko loops-break
*/
 
var random_new = $loader.loadprim("std@random_new", 0);
var random_int = $loader.loadprim("std@random_int", 2);
 
var random = random_new();
 
while true {
var r = random_int(random, 20);
$print(r, " ");
 
if r == 10 break;
 
r = random_int(random, 20);
$print(r, " ");
}
$print("\n");</syntaxhighlight>
 
{{out}}
<pre>prompt$ nekoc loops-break.neko
prompt$ neko loops-break
0 8 17 12 4 18 7 6 19 11 13 6 12 7 6 6 6 18 14 7 18 10 15 6 9 5 4 14 10</pre>
 
=={{header|Nemerle}}==
{{trans|C#}}
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using Nemerle.Imperative;
 
module Break
{
Main() : void
{
def rnd = Random();
while (true)
{
def a = rnd.Next(20);
WriteLine(a);
when (a == 10) break;
def b = rnd.Next(20);
WriteLine(b);
}
}
}</syntaxhighlight>
 
=={{header|NetRexx}}==
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
say
say 'Loops/Break'
rn = Rexx
rnd = Random()
 
loop label lb forever
rn = rnd.nextInt(19)
say rn.right(3)'\-'
if rn = 10 then leave lb
rn = rnd.nextInt(19)
say rn.right(3)'\-'
end lb
say
</syntaxhighlight>
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">(until (= 10 (println (rand 20)))
(println (rand 20)))</syntaxhighlight>
 
=={{header|Nim}}==
{{trans|Python}}
<syntaxhighlight lang="nim">import random
 
while true:
let a = random(19)
echo a
if a == 10:
break
let b = random(19)
echo b</syntaxhighlight>
 
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 I=RND(20)
20 PRINT I
30 IF I=10 THEN STOP
40 PRINT RND(20)
50 GOTO 10</syntaxhighlight>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
while true {
let a = random int 0..19
print $a
if $a == 10 {break}
print (random int 0..19)
}
</syntaxhighlight>
 
=={{header|Oberon-2}}==
Works with oo2c Version 2
<syntaxhighlight lang="oberon2">
MODULE LoopBreak;
IMPORT
RandomNumbers,
Out;
 
PROCEDURE Do();
VAR
rn: LONGINT;
BEGIN
LOOP
rn := RandomNumbers.RND(20);
Out.LongInt(rn,0);Out.Ln;
IF rn = 10 THEN EXIT END;
rn := RandomNumbers.RND(20);
Out.LongInt(rn,0);Out.Ln
END
END Do;
 
BEGIN
Do
END LoopBreak.
</syntaxhighlight>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
while(true) {
a := (Float->Random() * 20.0)->As(Int);
a->PrintLine();
if(a = 10) {
break;
};
a := (Float->Random() * 20.0)->As(Int);
a->PrintLine();
}
</syntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml"># Random.self_init();;
- : unit = ()
 
Line 370 ⟶ 2,731:
13
10
Exception: Pervasives.Exit.</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">while(1)
a = floor(unifrnd(0,20, 1));
disp(a)
Line 381 ⟶ 2,742:
b = floor(unifrnd(0,20, 1));
disp(b)
endwhile</langsyntaxhighlight>
 
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">while(true) [
19 rand dup print ":" print
10 == ifTrue: [ break ]
19 rand print " " print
]</syntaxhighlight>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(import (otus random!))
 
(call/cc (lambda (break)
(let loop ()
(if (= (rand! 20) 10)
(break #t))
(print (rand! 20))
(loop))))
</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">/*REXX ****************************************************************
* Three Ways to leave a Loop
* ooRexx added the possibility to leave an outer loop
* without using a control variable
* 12.05.2013 Walter Pachl
**********************************************************************/
do i1=1 To 2 /* an outer loop */
Say 'i1='i1 /* tell where we are */
Call random ,,123 /* seed to be reproducable */
do forever /* inner loop */
a=random(19)
Say a
if a=6 then leave /* leaces the innermost loop */
end
end
 
do i2=1 To 2
Say 'i2='i2
Call random ,,123
do forever
a=random(19)
Say a
if a=6 then leave i2 /* leaves loop with control variable i2 */
end
end
 
Parse Version v
Select
When pos('ooRexx',v)>0 Then supported=1
Otherwise supported=0
End
If supported Then Do
Say 'Leave label-name is supported in' v
do Label i3 Forever
Say 'outer loop'
Call random ,,123
do forever
a=random(19)
Say a
if a=6 then leave i3 /* leaves loop with label name i3 */
end
end
End
Else
Say 'Leave label-name is probably not supported in' v</syntaxhighlight>
{{out}}
<pre>i1=1
14
14
5
6
i1=2
14
14
5
6
i2=1
14
14
5
6
Leave label-name is supported in REXX-ooRexx_4.1.2(MT) 6.03 28 Aug 2012
outer loop
14
14
5
6
</pre>
 
=={{header|Oz}}==
We can implement this either with recursion or with a special type of the for-loop. Both can be considered idiomatic.
<syntaxhighlight lang="oz">for break:Break do
R = {OS.rand} mod 20
in
{Show R}
if R == 10 then {Break}
else {Show {OS.rand} mod 20}
end
end</syntaxhighlight>
 
=={{header|PARI/GP}}==
<syntaxhighlight lang="parigp">while(1,
t=random(20);
print(t);
if(t==10, break);
print(random(20))
)</syntaxhighlight>
 
=={{header|Pascal}}==
See [[Loops/Break#Delphi | Delphi]]
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">while (1) {
my $a = int(rand(20));
print "$a\n";
Line 392 ⟶ 2,864:
my $b = int(rand(20));
print "$b\n";
}</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
{{libheader|Phix/basics}}
{{works with|Rakudo|#21 "Seattle"}}
{{Trans|Euphoria}}
<lang perl6>loop {
The rand() function returns a random integer from 1 to the integer provided.
my $n = (0..19).pick;
 
say $n;
<!--<syntaxhighlight lang="phix">-->
last if $n == 10;
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span>
say (0..19).pick;
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
}</lang>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"%g "</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">10</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"%g\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
 
{{out}}
<pre>
2 10
1 7
3 16
10
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/Loops/Break
by Galileo, 11/2022 #/
 
include ..\Utilitys.pmt
 
def ran rand * int enddef
 
true while
20 ran
dup print "\t" print
10 == if false else 20 ran ? true endif
endwhile</syntaxhighlight>
{{out}}
<pre>12 8
12 10
5 7
10
=== Press any key to exit ===</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">while (true) {
$a = rand(0,19);
echo "$a\n";
Line 411 ⟶ 2,917:
$b = rand(0,19);
echo "$b\n";
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Literally:
<syntaxhighlight lang="picolisp">(use R
(loop
(println (setq R (rand 1 19)))
(T (= 10 R))
(println (rand 1 19)) ) )</syntaxhighlight>
Shorter:
<syntaxhighlight lang="picolisp">(until (= 10 (println (rand 1 19)))
(println (rand 1 19)) )</syntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">int main(){
while(1){
int a = random(20);
Line 424 ⟶ 2,941:
write(b + "\n");
}
}</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
do forever;
k = trunc(random()*20);
put (k);
if k = 10 then leave;
k = trunc(random()*20);
put skip list (k);
end;
</syntaxhighlight>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Demonstrate breaking.
Wait for the escape key.
Shut down.
 
To demonstrate breaking:
Pick a number between 0 and 19.
Write the number to the console.
If the number is 10, break.
Pick another number between 0 and 19.
Write the other number to the console.
Repeat.
 
To write a number to the console:
Convert the number to a string.
Write the string to the console.</syntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">realtime srand % init RNG
{
rand 20 mod % generate number between 0 and 19
dup = % print it
10 eq { exit } if % exit if 10
} loop</syntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$r = New-Object Random
for () {
$n = $r.Next(20)
Line 435 ⟶ 2,990:
}
Write-Host $r.Next(20)
}</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">If OpenConsole()
 
Repeat
a = Random(19)
PrintN(Str(a))
If a = 10
Break
EndIf
b = Random(19)
PrintN(Str(b))
PrintN("")
ForEver
 
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</syntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">importfrom random import randrange
 
while True:
a = random.randrange(20)
print (a)
if a == 10:
break
b = random.randrange(20)
print (b)</langsyntaxhighlight>
 
=={{header|QB64}}==
''CBTJD'': 2020/03/14
<syntaxhighlight lang="qbasic">RANDOMIZE TIMER
DO
n = INT(RND * 20)
PRINT n,
IF n = 10 THEN
EXIT DO
ELSE
n = INT(RND * 20)
PRINT n
END IF
LOOP UNTIL 0</syntaxhighlight>
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
(define loop -> (if (= 10 (PRINT (random 20)))
true
(do (PRINT (random 20))
(loop))))
(loop)
</syntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">[ 20 random
dup echo sp
10 = if done
20 random echo cr
again ]</syntaxhighlight>
 
{{Out}}
 
<pre>16 9
9 14
11 16
14 13
14 17
16 19
13 11
10 </pre>
 
 
=={{header|R}}==
{{works with|R|2.8.1}}
<langsyntaxhighlight Rlang="r">sample0to19 <- function() sample(0L:19L, 1,replace=TRUE)
repeat
{
Line 461 ⟶ 3,078:
result2 <- sample0to19()
cat(result1, result2, "\n")
}</langsyntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(let loop ()
(let/ec break
(define a (random 20))
(displayln a)
(when (= a 10) (break))
(displayln (random 20))
(loop)))
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|#21 "Seattle"}}
<syntaxhighlight lang="raku" line>loop {
say my $n = (0..19).pick;
last if $n == 10;
say (0..19).pick;
}</syntaxhighlight>
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">REBOL [
Title: "Loop/Break"
URL: http://rosettacode.org/wiki/Loop/Break
]
 
random/seed 1 ; Make repeatable.
; random/seed now ; Uncomment for 'true' randomness.
 
r20: does [(random 20) - 1]
 
forever [
prin x: r20
if 10 = x [break]
print rejoin [" " r20]
]
print ""</syntaxhighlight>
 
{{out}}
<pre>14 11
19 15
6 11
12 11
3 14
10</pre>
 
=={{header|Red}}==
{{trans|REBOL}}
<syntaxhighlight lang="rebol">Red [
Title: "Loops/Break"
URL: http://rosettacode.org/wiki/Loops/Break
]
 
random/seed 2 ; Make repeatable. Delete line for 'true' randomness.
 
r20: does [(random 20) - 1]
 
forever [
prin x: r20
if 10 = x [break]
print rejoin [" " r20]
]
print ""</syntaxhighlight>
{{out}}
<pre>
2 15
0 0
1 11
6 14
4 14
10
</pre>
 
=={{header|Retro}}==
<syntaxhighlight lang="retro">doc{
A couple of helper functions to make the rest of the
code more readable.
}doc
 
: rand ( -n ) random 20 mod ;
: . ( n- ) putn space ;
 
doc{
One approach is to use a simple repeat/again loop, and
a conditional exit. For instance:
}doc
 
: foo ( - )
repeat rand dup . 10 = if; rand . again ;
 
doc{
The other approach uses a structured while loop with the
second printing handled by a conditional clause.
}doc
 
[ rand dup . 10 <> [ [ rand . ] ifTrue ] sip ] while
</syntaxhighlight>
 
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program demonstrates a FOREVER DO loop with a test to LEAVE (break). */
/*REXX's RANDOM BIF returns an integer.*/
do forever /*perform loop until da cows come home.*/
a=random(19) /*same as: random(0, 19) */
call charout , right(a, 5) /*show A right─justified, column 1.*/
if a==10 then leave /*is random #=10? Then cows came home.*/
b=random(19) /*same as: random(0, 19) */
say right(b, 5) /*show B right─justified, column 2.*/
end /*forever*/ /* [↑] CHAROUT , xxx writes to term.*/
/*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output}}
 
(A long run was chosen)
<pre>
1 0
16 3
8 15
11 8
12 14
15 4
0 0
6 11
15 5
14 0
18 16
15 0
14 5
3 5
9 4
4 4
17 6
4 10
6 2
9 13
12 6
14 16
17 0
8 6
9 2
0 6
9 9
12 8
11 3
11 4
7 1
3 13
4 8
14 14
14 13
12 7
1 0
16 15
8 19
12 7
18 9
7 18
19 13
6 2
6 7
2 1
8 2
9 7
6 13
19 15
10
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
while true
a = random(20)
see a + nl
if a = 10 exit ok
end
</syntaxhighlight>
 
=={{header|RPL}}==
RPL does not have any <code>BREAK</code> command. Flags are of great help to exit loops:
≪ 1 CF
'''WHILE''' 1 FC? '''REPEAT'''
RAND 20 * IP
DUP 1 DISP
'''IF''' 10 == '''THEN''' 1 SF '''ELSE'''
RAND 20 * IP
2 DISP '''END'''
'''END'''
The error handling mechanism provides another way to break a loop:
≪ '''IFERR'''
'''WHILE''' 1 '''REPEAT'''
RAND 20 * IP DUP 1 DISP
'''IF''' 10 == '''THEN''' 0 DUP / '''END'''
RAND 20 * IP 2 DISP
'''END'''
'''THEN''' DROP2 '''END'''
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">loop do
a = rand(20)
putsprint a
if a == 10
breakputs
endbreak
end
b = rand(20)
b = puts brand(20)
puts "\t#{b}"
end</lang>
end</syntaxhighlight>
or
<syntaxhighlight lang="ruby">loop do
print a = rand(20)
puts or break if a == 10
puts "\t#{rand(20)}"
end</syntaxhighlight>
 
{{out}}
<pre>
0 4
11 0
8 2
12 13
3 0
6 9
2 8
12 10
8 17
12 6
10
</pre>
 
=={{header|Rust}}==
{{libheader|rand}}
<syntaxhighlight lang="rust">// cargo-deps: rand
 
extern crate rand;
use rand::{thread_rng, Rng};
fn main() {
let mut rng = thread_rng();
loop {
let num = rng.gen_range(0, 20);
if num == 10 {
println!("{}", num);
break;
}
println!("{}", rng.gen_range(0, 20));
}
}</syntaxhighlight>
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">data _null_;
do while(1);
n=floor(uniform(0)*20);
put n;
if n=10 then leave; /* 'leave' to break a loop */
end;
run;</syntaxhighlight>
 
=={{header|Sather}}==
<syntaxhighlight lang="sather">-- help class for random number sequence
class RANDOM is
attr seed:INT;
 
create(seed:INT):SAME is
res:RANDOM := new;
res.seed := seed;
return res;
end;
-- this code is taken from rand's man (C)
next:INT is
seed := seed * 1103515245 + 12345;
return (seed/65536) % 32768;
end;
end;
 
class MAIN is
main is
a, b :INT;
rnd:RANDOM := #(1);
loop
a := rnd.next % 20;
#OUT + a + "\n";
if a = 10 then break!; end; -- here we break
b := rnd.next % 20;
#OUT + b + "\n";
end;
end;
end;</syntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">scala> import util.control.Breaks.{breakable, break}
{{works with|Scala|2.7}}
import util.control.Breaks.{breakable, break}
 
scala> import util.Random
A break library method is available in Scala 2.8 but not 2.7
import util.Random
 
scala> breakable {
<lang Scala>
| while(true) {
import scala.util.Random
| val a = Random.nextInt(20)
| println(a)
| if(a == 10)
| break
| val b = Random.nextInt(20)
| println(b)
| }
| }
5
4
10
</syntaxhighlight>
 
=={{header|Scheme}}==
val rand = new Random
<syntaxhighlight lang="scheme">
var doNext = true
(let loop ((first (random 20)))
(print first)
(if (not (= first 10))
(begin
(print (random 20))
(loop (random 20)))))
</syntaxhighlight>
 
Or by using call/cc to break out:
 
<syntaxhighlight lang="scheme">
while(doNext) {
(call/cc
val first = rand.nextInt(20)
(lambda (break)
println(first)
(let loop ((first (random 20)))
(print first)
(if (= first 10)
(break))
(print (random 20))
(loop (random 20)))))
</syntaxhighlight>
 
=={{header|Scilab}}==
if (first != 10) {
{{works with|Scilab|5.5.1}}
val second = rand.nextInt(20)
<syntaxhighlight lang="text">while %T
println(second)
a=int(rand()*20) // [0..19]
} else {
doNextprintf("%2d = false",a)
if a==10 then break; end
b=int(rand()*20)
printf("%2d\n",b)
end
printf("\n")</syntaxhighlight>
{{out}}
<pre style="height:20ex">
4 15
0 6
13 12
16 13
17 1
11 13
14 3
10
</pre>
 
=={{header|Seed7}}==
Seed7 has no goto statement and hidden gotos like break- and continue-statements are also omitted.
But this is not a problem. All programs with break-statements can be rewritten as structured programs without break.
Usually structured programs have better readability. If you are used to it writing programs without goto (and break) is easy.
The example below shows how easy a break can be avoided in this exercise. The loop ends, if the first random number
is 10. The second random number does never terminate the loop.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
local
var integer: number is 0;
begin
repeat
number := rand(0, 19);
writeln(number);
if number <> 10 then
writeln(rand(0, 19));
end if;
until number = 10;
end func;</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var lim = 20;
loop {
say (var n = lim.rand.int);
n == 10 && break;
say lim.rand.int;
}</syntaxhighlight>
 
=={{header|Simula}}==
{{works with|SIMULA-67}}
<syntaxhighlight lang="simula">! Loops/Break - simula67 - 08/03/2017;
begin
integer num,seed;
seed:=0;
while true do
begin
num:=randint(1,20,seed);
outint(num,2); outimage;
if num=10 then goto lab;
end;
lab:
end</syntaxhighlight>
{{out}}
<pre>
 1
 9
 8
10
</pre>
 
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">[
|first second done|
 
first := Random nextIntegerBetween:0 and:19.
Stdout print:first; cr.
(done := (first == 10)) ifFalse:[
second := Random nextIntegerBetween:0 and:19.
Stdout print:' '; print:second; cr.
].
done
] whileFalse</syntaxhighlight>
alternative:
<syntaxhighlight lang="smalltalk">[:exit |
|first|
 
Stdout printCR: (first := Random nextIntegerBetween:0 and:19).
first == 10 ifTrue:[ exit value:nil ].
Stdout print:' '; printCR: (Random nextIntegerBetween:0 and:19).
] loopWithExit.</syntaxhighlight>
or shorter (because <tt>ifTrue:</tt> sends #value to its arg):
<syntaxhighlight lang="smalltalk">[:exit |
|first|
 
Stdout printCR: (first := Random nextIntegerBetween:0 and:19).
first == 10 ifTrue:exit.
Stdout print:' '; printCR: (Random nextIntegerBetween:0 and:19).
] loopWithExit.</syntaxhighlight>
 
=={{header|Snabel}}==
Uses a ranged random generator as iterator.
<syntaxhighlight lang="snabel">
let: rnd 19 random;
 
@rnd {
$ str say
10 = &break when
@rnd pop str say
} for
</syntaxhighlight>
 
=={{header|SNOBOL4}}==
Most Snobols lack a built-in rand( ) function. Kludgy "Linux-only" implementation:
<syntaxhighlight lang="snobol"> input(.random,io_findunit(),1,"/dev/urandom")
while &ALPHABET random @rand
output = rand = rand - (rand / 20) * 20
eq(rand,10) :f(while)
end</syntaxhighlight>
 
Or using a library function:
 
<syntaxhighlight lang="snobol4">* rand(n) -> real x | 0 <= x < n
-include 'random.sno'
 
loop ne(output = convert(rand(20)'integer'),10) :s(loop)
end</syntaxhighlight>
 
=={{header|Spin}}==
{{works with|BST/BSTC}}
{{works with|FastSpin/FlexSpin}}
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<syntaxhighlight lang="spin">con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
 
obj
ser : "FullDuplexSerial.spin"
 
pub main | r, s
ser.start(31, 30, 0, 115200)
 
s := 1337 ' PRNG seed
 
repeat
r := ||?s // 20
ser.dec(r)
ser.tx(32)
if r == 10
quit
r := ||?s // 20
ser.dec(r)
ser.tx(32)
 
waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0)</syntaxhighlight>
{{out}}
<pre>
8 13 1 7 19 1 15 16 9 6 5 9 1 15 5 0 6 3 9 19 8 9 10
</pre>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "loopsbreak" )
@( description, "Show a loop which prints random numbers (each number newly" )
@( description, "generated each loop) from 0 to 19 (inclusive). If a number is" )
@( description, "10, stop the loop after printing it, and do not generate any" )
@( description, "further numbers. Otherwise, generate and print a second random" )
@( description, "number before restarting the loop. If the number 10 is never" )
@( description, "generated as the first number in a loop, loop forever. " )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Loops/Break" );
pragma license( unrestricted );
 
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
 
procedure arraysloop is
a : positive;
b : positive;
begin
loop
a := numerics.rnd( 20 );
put_line( strings.image( a ) );
exit when a = 10;
b := numerics.rnd( 20 );
put_line( strings.image( b ) );
end loop;
end arraysloop;</syntaxhighlight>
 
=={{header|SPL}}==
Direct approach:
<syntaxhighlight lang="spl">>
n = #.rnd(20)
#.output(n)
<< n=10
n = #.rnd(20)
#.output(n)
<</syntaxhighlight>
With reusable code:
<syntaxhighlight lang="spl">>
:1
n = #.rnd(20)
#.output(n)
<-
<< n=10
1 <->
<</syntaxhighlight>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<syntaxhighlight lang="sql pl">
--#SET TERMINATOR @
 
SET SERVEROUTPUT ON@
 
BEGIN
DECLARE VAL INTEGER;
LOOP: WHILE (TRUE = TRUE) DO
SET VAL = INTEGER(RAND() * 20);
CALL DBMS_OUTPUT.PUT_LINE(VAL);
IF (VAL = 10) THEN
LEAVE LOOP;
END IF;
SET VAL = INTEGER(RAND() * 20);
CALL DBMS_OUTPUT.PUT_LINE(VAL);
END WHILE LOOP;
END @
</syntaxhighlight>
Output:
<pre>
db2 -td@
db2 => SET SERVEROUTPUT ON@
DB20000I The SET SERVEROUTPUT command completed successfully.
db2 => BEGIN
...
db2 (cont.) => END @
DB20000I The SQL command completed successfully.
 
4
16
9
1
10
</pre>
Since V11.1, the builtin module can be used instead of RAND, like this:
<syntaxhighlight lang="sql pl">
SET VAL = CALL DBMS_RANDOM.VALUE(0,20);
</syntaxhighlight>
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">while 1 {
local n=runiformint(0,19)
display `n'
if `n'==10 continue, break
display runiformint(0,19)
}</syntaxhighlight>
 
=== Mata ===
<syntaxhighlight lang="stata">for (; 1; ) {
printf("%f\n",n=runiformint(1,1,0,19))
if (n==10) break
printf("%f\n",runiformint(1,1,0,19))
}</syntaxhighlight>
 
=={{header|Suneido}}==
<syntaxhighlight lang="suneido">forever
{
Print(i = Random(20))
if i is 10
break
Print(i = Random(20))
}
</syntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">while true
{
let a = Int(arc4random()) % (20)
print("a: \(a)",terminator: " ")
if (a == 10)
{
break
}
let b = Int(arc4random()) % (20)
print("b: \(b)")
}
</syntaxhighlight>{{out}}
</lang>
<pre>
a: 2 b: 7
a: 16 b: 13
a: 18 b: 16
a: 10
</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">while true {
set a [expr int(20*rand())]
puts $a
if {$a == 10} {
break
}
set b [expr int(20*rand())]
puts $b
}</syntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
<langsyntaxhighlight lang="ti89b">Local x
Loop
rand(20)-1 → x
Line 509 ⟶ 3,739:
EndIf
Output 64, 50, rand(20)-1 © paint text to the right on same line
EndLoop</langsyntaxhighlight>
 
=={{header|TclTorqueScript}}==
 
<lang tcl>while true {
<syntaxhighlight lang="torque">for(%a = 0; %a > -1; %a++)
set a [expr int(20*rand())]
{
puts $a
if%number {$a == 10}getRandom(0, {19);
if(%number == break10)
break;
}</syntaxhighlight>
 
=={{header|Transact-SQL}}==
 
<syntaxhighlight lang="transact-sql">
DECLARE @i INT;
WHILE 1=1
BEGIN
SET @i = ABS(CHECKSUM(NewId())) % 20;
PRINT @i;
IF @i=10 BREAK;
PRINT ABS(CHECKSUM(NewId())) % 20;
END;
</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
LOOP
a=RANDOM_NUMBERS (0,19,1)
IF (10==a) THEN
PRINT "a=",a
STOP
ELSE
b=RANDOM_NUMBERS (0,19,1)
PRINT "a=",a," b=",b
ENDIF
IF (10==a,b) STOP
ENDLOOP
</syntaxhighlight>
{{out}}
<pre>
a=0 b=17
a=11 b=13
a=3 b=16
a=17 b=13
a=8 b=11
a=8 b=0
a=6 b=2
a=10
</pre>
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Do
n = RND(20)
Print n
Until n = 10
Print RND(20)
Loop</syntaxhighlight>
 
=={{header|UNIX Shell}}==
This script gets random numbers from jot(1).
If there is any error with jot(1), the script exits.
 
{{works with|Bourne Shell}}
{{libheader|jot}}
<syntaxhighlight lang="bash">while true; do
a=`jot -w %d -r 1 0 20` || exit $?
echo $a
test 10 -eq $a && break
b=`jot -w %d -r 1 0 20` || exit $?
echo $b
done</syntaxhighlight>
 
Korn Shells have a RANDOM parameter.
 
{{works with|Bash}}
{{works with|pdksh|5.2.14}}
<syntaxhighlight lang="bash">while true; do
echo $((a=RANDOM%20))
[ $a -eq 10 ] && break
echo $((b=RANDOM%20))
done</syntaxhighlight>
 
=={{header|Ursa}}==
{{trans|Python}}
<syntaxhighlight lang="ursa">decl ursa.util.random r
decl int a b
while true
set a (r.getint 19)
out a endl console
if (= a 10)
break
end while
set b (r.getint 19)
out b endl console
end while</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Public Sub LoopsBreak()
Dim value As Integer
Randomize
Do While True
value = Int(20 * Rnd)
Debug.Print value
If value = 10 Then Exit Do
Debug.Print Int(20 * Rnd)
Loop
End Sub</syntaxhighlight>
 
=={{header|VBScript}}==
Based on BASIC version. Demonstrates breaking out of Do/Loop and For/Next (Exit is good for getting out of functions and subs as well).
 
<syntaxhighlight lang="vb">Dim a, b, i
 
Do
a = Int(Rnd * 20)
WScript.StdOut.Write a
If a = 10 Then Exit Do
b = Int(Rnd * 20)
WScript.Echo vbNullString, b
Loop
 
For i = 1 To 100000
a = Int(Rnd * 20)
WScript.StdOut.Write a
If a = 10 Then Exit For
b = Int(Rnd * 20)
WScript.Echo vbNullString, b
Next</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Program
Sub Main()
' Initialize with seed 0 to get deterministic output (may vary across .NET versions, though).
Dim rand As New Random(0)
 
Do
Dim first = rand.Next(20) ' Upper bound is exclusive.
Console.Write(first & " ")
 
If first = 10 Then Exit Do
 
Dim second = rand.Next(20)
Console.Write(second & " ")
Loop
End Sub
End Module</syntaxhighlight>
{{out}}
<pre>14 16 15 11 4 11 18 8 19 5 5 9 12 9 19 0 17 19 13 6 16 16 19 0 13 10 18 13 10 </pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import rand
import rand.seed
 
fn main() {
rand.seed(seed.time_seed_array(2))
for {
a := rand.intn(20)?
println(a)
if a == 10 {
break
}
b := rand.intn(20)?
println(b)
}
}</syntaxhighlight>
set b [expr int(20*rand())]
 
puts $b
=={{header|Wren}}==
}</lang>
<syntaxhighlight lang="wren">import "random" for Random
 
var r = Random.new()
while (true) {
var n = r.int(20)
System.print(n)
if (n == 10) break
System.print(r.int(20))
} </syntaxhighlight>
 
{{out}}
A (mercifully short) sample run:
<pre>
1
0
13
16
2
0
10
</pre>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "loopbreak"
 
IMPORT "xst" ' for XstGetSystemTime
 
DECLARE FUNCTION Entry()
 
' Pseudo-random number generator
' Based on the rand, srand functions from Kernighan & Ritchie's book
' 'The C Programming Language'
DECLARE FUNCTION Rand()
DECLARE FUNCTION SRand(seed%%)
 
FUNCTION Entry()
XstGetSystemTime (@msec)
SRand(INT(msec) MOD 32768)
DO
a%% = Rand() MOD 20
PRINT FORMAT$("##", a%%);
IF a%% = 10 THEN EXIT DO
b%% = Rand() MOD 20
PRINT FORMAT$(" ##", b%%)
LOOP
PRINT
END FUNCTION
 
' Return pseudo-random integer on 0..32767
FUNCTION Rand()
#next&& = #next&& * 1103515245 + 12345
END FUNCTION USHORT(#next&& / 65536) MOD 32768
 
' Set seed for Rand()
FUNCTION SRand(seed%%)
#next&& = seed%%
END FUNCTION
 
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
17 3
3 8
9 7
18 5
4 0
9 16
0 19
5 18
12 16
1 1
10
</pre>
 
=={{header|XBS}}==
<syntaxhighlight lang="xbs">while(true){
set n:number = math.random(0,19);
log(`first: {n}`);
if(n==10){stop}
n = math.random(0,19);
log(`second: {n}`);
}</syntaxhighlight>
{{out}}
<pre>
first: 0
second: 13
first: 11
second: 10
first: 16
second: 3
first: 8
second: 19
first: 7
second: 10
first: 10
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int N;
loop [N:= Ran(20);
IntOut(0, N);
if N=10 then quit;
ChOut(0, 9\tab\);
IntOut(0, Ran(20));
CrLf(0);
]</syntaxhighlight>
 
{{out}}
<pre>
7 17
13 2
2 10
0 4
2 9
15 15
14 19
10
</pre>
 
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">do
i = int(ran(19))
print i using "##";
print " ";
if i = 10 then break : fi
i = int(ran(19))
print i using "##", " ";
loop
print
end</syntaxhighlight>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() !void {
const RndGen = std.rand.DefaultPrng;
var rnd = RndGen.init(42);
// possible improvement: make rng fair
var rand_num1: u5 = undefined;
var rand_num2: u5 = undefined;
while (true) {
rand_num1 = rnd.random().int(u5) % 20;
try std.io.getStdOut().writer().print("{d}\n", .{rand_num1});
if (rand_num1 == 10)
break;
rand_num2 = rnd.random().int(u5) % 20;
try std.io.getStdOut().writer().print("{d}\n", .{rand_num2});
}
}</syntaxhighlight>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">while(1){n:=(0).random(20); n.print(" ");
if (n==10){ println(); break; } (0).random().println();
}</syntaxhighlight>
{{out}}
<pre>
7 2139341079
4 3217334923
18 2050357211
2 2061361000
10
</pre>
 
{{omit from|GUISS}}
889

edits