Loops/Nested: Difference between revisions

m
No edit summary
m (→‎{{header|Wren}}: Minor tidy)
 
(105 intermediate revisions by 58 users not shown)
Line 1:
{{task|Iteration}} [[Category:Loop modifiers]]
 
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over <math>[1,\ldots,20]</math>.
 
The loops iterate rows and columns of the array printing the elements until the value <math>20</math> is met.
 
Specifically, this task also shows how to [[Loop/Break|break]] out of nested loops.
 
 
;Related tasks:
* &nbsp; [[Loop over multiple arrays simultaneously]]
* &nbsp; [[Loops/Break]]
* &nbsp; [[Loops/Continue]]
* &nbsp; [[Loops/Do-while]]
* &nbsp; [[Loops/Downward for]]
* &nbsp; [[Loops/For]]
* &nbsp; [[Loops/For with a specified step]]
* &nbsp; [[Loops/Foreach]]
* &nbsp; [[Loops/Increment loop index within loop body]]
* &nbsp; [[Loops/Infinite]]
* &nbsp; [[Loops/N plus one half]]
* &nbsp; [[Loops/Nested]]
* &nbsp; [[Loops/While]]
* &nbsp; [[Loops/with multiple ranges]]
* &nbsp; [[Loops/Wrong ranges]]
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">[[Int]] mat
L 10
mat [+]= (1..10).map(x -> random:(1..20))
 
L(row) mat
L(el) row
print(el, end' ‘ ’)
I el == 20
L(row).break</syntaxhighlight>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Loop nested 12/08/2015
LOOPNEST CSECT
USING LOOPNEST,R12
Line 78 ⟶ 111:
RANDSEED DC F'16807' running n
YREGS
END LOOPNEST</langsyntaxhighlight>
{{out}}
<pre> 3 4 1 11 13 17 11 9 8 2 15 19 16 18 1 9 7 16 12 3
11 13 13 6 13 19 9 18 11 4 7 8 6 7 2 10 14 4 5 1
16 14 13 6 11 20</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
DEFINE PTR="CARD"
BYTE i,j,found
PTR ARRAY a(10)
BYTE ARRAY tmp,
a0(10),a1(10),a2(10),a3(10),a4(10),
a5(10),a6(10),a7(10),a8(10),a9(10)
 
a(0)=a0 a(1)=a1 a(2)=a2 a(3)=a3 a(4)=a4
a(5)=a5 a(6)=a6 a(7)=a7 a(8)=a8 a(9)=a9
 
FOR j=0 TO 9
DO
tmp=a(j)
FOR i=0 TO 9
DO
tmp(i)=Rand(20)+1
OD
OD
 
found=0
FOR j=0 TO 9
DO
tmp=a(j)
FOR i=0 TO 9
DO
PrintB(tmp(i)) Put(32)
IF tmp(i)=20 THEN
found=1 EXIT
FI
OD
IF found THEN
EXIT
FI
PutE()
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Loops_nested.png Screenshot from Atari 8-bit computer]
<pre>
12 10 16 15 19 7 1 18 3 11
18 3 7 12 18 17 16 12 14 7
14 5 19 8 9 4 6 12 12 2
15 9 9 1 17 17 2 8 8 14
2 14 14 5 5 6 20
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
 
Line 105 ⟶ 186:
New_Line;
end loop Outer;
end Test_Loop_Nested;</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 111 ⟶ 192:
5 5 17 15 17 2 5 5 17 13
16 10 10 20
</pre>
 
=={{header|ALGOL 60}}==
{{works with|ALGOL 60|OS/360}}
<syntaxhighlight lang="algol60">'BEGIN' 'COMMENT' Loops/Nested - ALGOL60 - 19/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' 'ARRAY' A(/1:10,1:10/);
'INTEGER' I,J;
SEED:=31569;
'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO'
'FOR' J:=1 'STEP' 1 'UNTIL' 10 'DO'
A(/I,J/):=RANDOM(20);
SYSACT(1,6,120);SYSACT(1,8,60);SYSACT(1,12,1);'COMMENT' open print;
'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO'
'FOR' J:=1 'STEP' 1 'UNTIL' 10 'DO' 'BEGIN'
OUTINTEGER(1,A(/I,J/));
'IF' A(/I,J/)=20 'THEN' 'GOTO' LAB;
'END';
LAB:
'END'</syntaxhighlight>
{{out}}
<pre>
+19 +5 +1 +4 +17 +6 +2 +18 +12
+3 +13 +6 +8 +6 +10 +9 +15 +20
</pre>
 
Line 118 ⟶ 229:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
<langsyntaxhighlight lang="algol68">main: (
[10][10]INT a; INT i, j;
 
Line 137 ⟶ 248:
xkcd com 292:
print(new line)
)</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 144 ⟶ 255:
12 20
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <jambo.h>
 
#define DIMS 10
Main
Unset decimal
Dim (DIMS,DIMS) as ceil rand (20,t)
 
Set decimal '0'
Printnl ("ORIGINAL MATRIX:\n", Just right (3, Str(t)), "\n")
 
aux=0
Loop for ( i=1, #(i<=DIMS && aux<>20 ), ++i)
Loop for ( j=1, #(j<=DIMS), ++j)
When ( Equals ( 20, [i,j] Get 't' ---Copy to 'aux'---) ) { Break }
/*
Also: When( #( ((aux:= (t[i,j])) == 20) ) ) { Break }
*/
Just right (3, Str(aux)), Print only if ( #(DIMS-j), "," )
Next
Prnl
Next
Printnl ("\nFOUNDED: ", i,",",j," = ",aux)
End
</syntaxhighlight>
{{out}}
<pre>
ORIGINAL MATRIX:
16, 5, 15, 19, 14, 15, 12, 15, 10, 19
6, 8, 17, 1, 5, 13, 14, 4, 15, 5
10, 17, 8, 4, 9, 19, 14, 17, 7, 4
7, 2, 8, 1, 20, 1, 15, 12, 16, 4
10, 2, 12, 7, 3, 16, 19, 16, 19, 14
1, 9, 11, 9, 12, 19, 7, 6, 16, 13
9, 2, 15, 16, 2, 15, 17, 17, 7, 13
20, 17, 15, 12, 3, 17, 8, 2, 13, 7
15, 13, 15, 6, 2, 7, 5, 8, 12, 20
1, 20, 1, 16, 16, 2, 10, 12, 19, 17
 
 
16, 5, 15, 19, 14, 15, 12, 15, 10, 19
6, 8, 17, 1, 5, 13, 14, 4, 15, 5
10, 17, 8, 4, 9, 19, 14, 17, 7, 4
7, 2, 8, 1,
 
FOUNDED: 4,5 = 20
 
</pre>
 
=={{header|AppleScript}}==
AppleScript has <tt>exit repeat</tt> to break out of a single loop prematurely, but nothing specifically for nested loops. So either <tt>exit repeat</tt> must be used twice …
<syntaxhighlight lang="applescript">on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
set inRow to item i of array
set outRow to {}
repeat with j from 1 to (count inRow)
set n to item j of inRow
set end of outRow to n
if (n = stopVal) then exit repeat # <--
end repeat
set end of out to outRow
if (n = stopVal) then exit repeat # <--
end repeat
return out
end loopDemo</syntaxhighlight>
… or of course one or both loops can be specified to terminate at the critical juncture anyway …
<syntaxhighlight lang="applescript">on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
set inRow to item i of array
set len to (count inRow)
set n to beginning of inRow
set outRow to {n}
set j to 2
repeat until ((j > len) or (n = stopVal)) # <--
set n to item j of inRow
set end of outRow to n
set j to j + 1
end repeat
set end of out to outRow
if (n = stopVal) then exit repeat # <--
end repeat
return out
end loopDemo</syntaxhighlight>
… or, with the process in a dedicated handler, it can be returned from directly at any point:
<syntaxhighlight lang="applescript">on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
set inRow to item i of array
set outRow to {}
repeat with j from 1 to (count inRow)
set n to item j of inRow
set end of outRow to n
if (n = stopVal) then return out & {outRow} # <--
end repeat
set end of out to outRow
end repeat
return out
end loopDemo</syntaxhighlight>
 
Demo:
<syntaxhighlight lang="applescript">local array, stopVal, row
set array to {}
set stopVal to 20
repeat 10 times
set row to {}
repeat 10 times
set end of row to (random number from 1 to stopVal)
end repeat
set end of array to row
end repeat
loopDemo(array, stopVal) -- Any of the handlers above.</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{{15, 8, 9, 8, 9, 9, 10, 16, 3, 6}, {11, 3, 14, 18, 17, 1, 16, 15, 14, 7}, {4, 20}}</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program loopnested.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
 
 
.equ NBVALUECOL, 10
.equ NBLIGNES, 10
.equ MAXVALUE, 20
 
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .ascii " "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
 
.align 4
iGraine: .int 314159
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
tiValues: .skip 4 * NBVALUECOL * NBLIGNES
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r3,iAdrtiValues
mov r4,#0 @ loop indice
mov r5,#0
mov r7,#4 * NBVALUECOL
1: @ begin loop 1
mov r0,#MAXVALUE + 1
bl genereraleas @ result 0 to MAXVALUE
mul r6,r5,r7
add r6,r4,lsl #2
str r0,[r3,r6]
add r4,#1
cmp r4,#NBVALUECOL
blt 1b
mov r4,#0
add r5,#1
cmp r5,#NBLIGNES
blt 1b
 
mov r4,#0 @ loop indice
mov r5,#0 @ total
ldr r3,iAdrtiValues @ table values address
2:
mul r6,r5,r7
add r6,r4,lsl #2
ldr r0,[r3,r6]
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call conversion decimal
mov r1,#0
ldr r0,iAdrsMessResult
strb r1,[r0,#4]
ldr r0,iAdrsMessResult
bl affichageMess @ display message
ldr r0,[r3,r6]
cmp r0,#MAXVALUE
beq 3f
add r4,#1
cmp r4,#NBVALUECOL
blt 2b
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
mov r4,#0
add r5,#1
cmp r5,#NBLIGNES
blt 2b
b 100f
3:
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrtiValues: .int tiValues
 
/******************************************************************/
/* 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 unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
/***************************************************/
/* 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
cmp r0,#0
beq 100f
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="arturo">printTable: function [tbl][
; wrapping the nested loop in a function
; allows us to use return to exit all of the loops
; since `break` only exits the inner loop
loop 0..dec size tbl 'x [
loop 0..dec size tbl\[x] 'y [
prints pad to :string tbl\[x]\[y] 2
if tbl\[x]\[y] = 20 -> return ø
prints ", "
]
print ""
]
]
 
a: []
loop 1..10 'x [
row: []
loop 1..10 'y [
'row ++ random 1 20
]
'a ++ @[row]
]
 
printTable a</syntaxhighlight>
 
{{out}}
 
<pre> 4, 12, 12, 17, 7, 13, 14, 10, 14, 9,
17, 12, 16, 10, 11, 13, 8, 13, 17, 3,
6, 17, 3, 18, 2, 16, 7, 9, 19, 9,
19, 11, 11, 14, 5, 14, 18, 17, 19, 15,
17, 16, 8, 3, 14, 17, 5, 6, 8, 1,
8, 4, 9, 10, 16, 16, 4, 15, 10, 18,
5, 8, 15, 19, 7, 8, 2, 6, 10, 8,
4, 17, 15, 18, 14, 2, 20</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, 10
{
i := A_Index
Line 169 ⟶ 671:
finish:
MsgBox % "a[" . i . "][" . j . "]" is 20
Return</langsyntaxhighlight>
 
=={{header|AWK}}==
To break from two loops, this program uses two <tt>break</tt> statements and one <tt>b</tt> flag.
<langsyntaxhighlight lang="awk">BEGIN {
rows = 5
columns = 5
Line 198 ⟶ 700:
print
}
}</langsyntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang="qbasic">DIM a(1 TO 10, 1 TO 10) AS INTEGER
CLS
FOR row = 1 TO 10
Line 215 ⟶ 717:
IF a(row, col) = 20 THEN END
NEXT col
NEXT row</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic"> 1 C = 5
2 R = 4
3 C = C - 1:R = C - 1: DIM A(C,R)
4 FOR J = 0 TO R: FOR I = 0 TO C:N = N + 1:A(I,J) = N: NEXT I,J
5 FOR J = 0 TO R: FOR I = 0 TO C:X = INT ( RND (1) * C):Y = INT ( RND (1) * R):N = A(I,J):A(I,J) = A(X,Y):A(X,Y) = N: NEXT I,J
6 FOR J = 0 TO R
7 FOR I = 0 TO C
8 PRINT S$A(I,J);:S$ = " "
9 IF A(I,J) < > 20 THEN NEXT I,J</syntaxhighlight>
==={{header|Commodore BASIC}}===
We should END gracefully. (The Sinclair example below will produce an error on any Commodore machine.)
 
Also... What if no 20 is ever found?
 
<syntaxhighlight lang="commodorebasicv2">
10 dim a$(20,20):print "initializing...":print
20 for r=1 to 20:for c=1 to 20
30 a$(r,c)=chr$(int(rnd(1)*20)+1)
40 next c,r
50 rem now search array
60 for r=1 to 20:for c=1 to 20
70 e=asc(a$(r,c))
80 print "(";r;","c;") =";e
90 if e=20 then print "found 20. stopping search.":end
100 next c,r
110 print "search complete. no 20 found.":end
</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM.
 
A couple of points to note: (1) since the values we want are small enough to fit into an unsigned byte, we cast them to characters and store them in an array of strings—thereby using only a fifth of the storage space that an array of numbers would take up; (2) the <code>GOTO</code> statement in line <tt>100</tt> breaks out of both the enclosing loops and also, since its target is higher than any line number in the program, causes execution to terminate normally.
 
<syntaxhighlight lang="basic"> 10 DIM A$(20,20)
20 FOR I=1 TO 20
30 FOR J=1 TO 20
40 LET A$(I,J)=CHR$ (1+INT (RND*20))
50 NEXT J
60 NEXT I
70 FOR I=1 TO 20
80 FOR J=1 TO 20
90 PRINT CODE A$(I,J);" ";
100 IF CODE A$(I,J)=20 THEN GOTO 130
110 NEXT J
120 NEXT I</syntaxhighlight>
 
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">dim a(20, 20)
 
for i = 0 to 19
for j = 0 to 19
a[i, j] = int(rand * 20) + 1
next j
next i
 
for i = 0 to 19
for j = 0 to 19
print a[i, j];" ";
if a[i, j] = 20 then end
next j
next i
 
end</syntaxhighlight>
 
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM array(10,10)
FOR row% = 0 TO 10
FOR col% = 0 TO 10
Line 231 ⟶ 800:
NEXT
NEXT row%
</syntaxhighlight>
</lang>
EXIT FOR can jump out of multiple nested loops by specifying a control variable.
 
Line 237 ⟶ 806:
Arrays have only one dimension, so we use ''a[i * c + j]'' instead of ''a[i, j]''.
{{trans|AWK}}
<langsyntaxhighlight lang="bc">s = 1 /* Seed of the random number generator */
 
/* Random number from 1 to 20. */
Line 282 ⟶ 851:
"
}
quit</langsyntaxhighlight>
 
=={{header|C}}==
Using goto (note: gotos are [http://en.wikipedia.org/wiki/Considered_harmful considered harmful]):
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <time.h>
#include <stdio.h>
Line 309 ⟶ 878:
printf("\n");
return 0;
}</langsyntaxhighlight>
 
Using break, the preferred alternative to goto
=={{header|C++}}==
<syntaxhighlight lang="c">
{{works with|C++11}}
<lang cpp>#include <cstdlibstdlib.h>
#include <ctimetime.h>
#include <iostreamstdio.h>
 
int main() {
using namespace std;
int a[10][10], i, j;
int main()
{
int arr[10][10];
srand(time(NULL));
for (auto&i = 0; i < row:10; arri++)
for (auto&j = 0; j < col:10; rowj++)
cola[i][j] = rand() % 20 + 1;
 
for ([&](i = 0; i < 10; i++) {
for (auto&j row= :0; arrj < 10; j++) {
for printf(auto&" col:%d", rowa[i][j]);
{ if (a[i][j] == 20)
cout << col << endlbreak;
if(col == 20)return;}
if (a[i][j] == }20)
})() break;
printf("\n");
}
printf("\n");
return 0;
}
}</lang>
</syntaxhighlight>
 
=={{header|C sharp|C#}}==
Uses goto as C# has no way to break from multiple loops
<langsyntaxhighlight lang="csharp">using System;
 
class Program {
Line 348 ⟶ 920:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 2021) + 1;
}
}
Line 364 ⟶ 936:
Console.WriteLine();
}
}</langsyntaxhighlight>
 
 
Same using Linq :
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
 
// prepare linq statement with two 'from' which makes nested loop
var pairs = from i in Enumerable.Range(0, 10)
from j in Enumerable.Range(0, 10)
select new { i = i, j = j};
 
// iterates through the full nested loop with a sigle foreach statement
foreach (var p in pairs)
{
a[p.i, p.j] = r.Next(0, 21) + 1;
}
 
// iterates through the nested loop until find element = 20
pairs.Any(p => { Console.Write(" {0}", a[p.i, p.j]); return a[p.i, p.j] == 20; });
Console.WriteLine();
}
}</syntaxhighlight>
 
=={{header|C++}}==
Lambda call:
{{works with|C++11}}
<syntaxhighlight lang="cpp">#include<cstdlib>
#include<ctime>
#include<iostream>
 
using namespace std;
int main()
{
int arr[10][10];
srand(time(NULL));
for(auto& row: arr)
for(auto& col: row)
col = rand() % 20 + 1;
 
([&](){
for(auto& row : arr)
for(auto& col: row)
{
cout << col << endl;
if(col == 20)return;
}
})();
return 0;
}</syntaxhighlight>
Goto statement:
{{works with|C++11}}
<syntaxhighlight lang="cpp">#include<cstdlib>
#include<ctime>
#include<iostream>
 
using namespace std;
int main()
{
int arr[10][10];
srand(time(NULL));
for(auto& row: arr)
for(auto& col: row)
col = rand() % 20 + 1;
 
for(auto& row : arr) {
for(auto& col: row) {
cout << ' ' << col;
if (col == 20) goto out;
}
cout << endl;
}
out:
 
return 0;
}</syntaxhighlight>
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">use Random;
 
var nums:[1..10, 1..10] int;
Line 382 ⟶ 1,035:
}
writeln();
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
We explicitly return a status flag from the inner loop:
<langsyntaxhighlight lang="clojure">(ns nested)
 
(defn create-matrix [width height]
Line 403 ⟶ 1,056:
(when rs (recur rs)))))
 
(print-matrix (create-matrix 10 10))</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Nested-Loop.
 
Line 450 ⟶ 1,103:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
<langsyntaxhighlight lang="cfm">
<Cfset RandNum = 0>
<Cfloop condition="randNum neq 20">
Line 463 ⟶ 1,116:
<br>
</Cfloop>
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(let ((a (make-array '(10 10))))
(dotimes (i 10)
(dotimes (j 10)
Line 479 ⟶ 1,132:
(return-from outer)))
(terpri))
(terpri)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random;
 
void main() {
Line 499 ⟶ 1,152:
 
writeln();
}</langsyntaxhighlight>
 
=={{header|Delphi}}/{{header|Pascal}}==
<lang delphi>var
matrix: array[1..10,1..10] of Integer;
row, col: Integer;
broken: Boolean;
begin
// Launch random number generator
randomize;
// Filling matrix with random numbers
for row := 1 to 10 do
for col := 1 to 10 do
matrix[row, col] := Succ(Random(20));
// Displaying values one by one, until at the end or reached number 20
Broken := False;
for row := 1 to 10 do
begin
for col := 1 to 10 do
begin
ShowMessage(IntToStr(matrix[row, col]));
if matrix[row, col] = 20 then
begin
Broken := True;
break;
end;
end;
if Broken then break;
end;
end;</lang>
 
=={{header|dc}}==
A single ''Q'' command can break multiple nested loops.
{{trans|bc}}
<langsyntaxhighlight lang="dc">1 ss [Seed of the random number generator.]sz
 
[*
Line 600 ⟶ 1,224:
]sL
0 d si [i = 0]sz
lb >L [Enter outer loop.]sz</langsyntaxhighlight>
In this program, ''li lj + 3 + Q'' breaks both the inner loop and the outer loop. We must count how many levels of string execution to break. Our loops use tail recursion, so each iteration is a level of string execution. We have i + 1 calls to outer loop L, and j + 1 calls to inner loop I, and 1 call to condition D; so we break i + j + 3 levels with ''li lj + 3 + Q''.
 
=={{header|Delphi}}/{{header|Pascal}}==
<syntaxhighlight lang="delphi">var
matrix: array[1..10,1..10] of Integer;
row, col: Integer;
broken: Boolean;
begin
// Launch random number generator
randomize;
// Filling matrix with random numbers
for row := 1 to 10 do
for col := 1 to 10 do
matrix[row, col] := Succ(Random(20));
// Displaying values one by one, until at the end or reached number 20
Broken := False;
for row := 1 to 10 do
begin
for col := 1 to 10 do
begin
ShowMessage(IntToStr(matrix[row, col]));
if matrix[row, col] = 20 then
begin
Broken := True;
break;
end;
end;
if Broken then break;
end;
end;</syntaxhighlight>
 
=={{header|Dyalect}}==
 
There is no direct way to break out of a nested loop in Dyalect, <code>goto</code> is also not supported, however the desired effect can be achieved by placing a nested loop in an expression context and make it return <code>true</code> if we need to break out of the parent loop:
 
<syntaxhighlight lang="dyalect">let array = [[2, 12, 10, 4], [18, 11, 20, 2]]
for row in array {
break when {
for element in row {
print("\(element)")
if element == 20 {
break true
}
}
}
}
print("*Done")</syntaxhighlight>
 
{{out}}
 
<pre>2
12
10
4
18
11
20
*Done</pre>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def array := accum [] for i in 1..5 { _.with(accum [] for i in 1..5 { _.with(entropy.nextInt(20) + 1) }) }
 
escape done {
Line 617 ⟶ 1,299:
}
}
println("done.")</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
arr[][] = [ [ 2 12 10 4 ] [ 18 11 20 2 ] ]
for i to len arr[][]
for j to len arr[i][]
if arr[i][j] = 20
print "20 at " & i & "," & j
break 2
.
.
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(lib 'math) ;; for 2D-arrays
(define array (build-array 42 42 (lambda(i j) (1+ (random 20)))))
Line 629 ⟶ 1,324:
→ 9 8 11 1 14 11 1 9 16 1 10 5 5 6 5 4 13 17 14 13 6 10 16 4 8 5 1 17 16 19 4 6 18 1 15 3 4 13 19
6 12 5 5 17 19 16 3 7 2 15 16 14 16 16 19 18 14 16 6 18 14 17 20
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<lang elixir>defmodule Loops do
<syntaxhighlight lang="elixir">defmodule Loops do
def nested do
:random.seed(:os.timestamp)
list = Enum.shuffle(1..20) |> Enum.chunk(5)
IO.inspect list, char_lists: :as_lists
Line 655 ⟶ 1,350:
end
 
Loops.nested</langsyntaxhighlight>
 
{{out|Sample output}}
Line 663 ⟶ 1,358:
8 7 12 17 9
6 20 done
</pre>
 
'''used Enum.any?'''
<syntaxhighlight lang="elixir">list = Enum.shuffle(1..20) |> Enum.chunk(5)
IO.inspect list, char_lists: :as_lists
Enum.any?(list, fn row ->
IO.puts ""
Enum.any?(row, fn x ->
IO.write "#{x} "
x == 20
end)
end)
IO.puts "done"</syntaxhighlight>
 
{{out|Sample output}}
<pre>
[[17, 15, 18, 14, 16], [5, 11, 10, 4, 2], [8, 20, 7, 19, 1], [6, 9, 3, 12, 13]]
 
17 15 18 14 16
5 11 10 4 2
8 20 done
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( loops_nested ).
 
Line 688 ⟶ 1,404:
 
random_array( Size ) -> [random:uniform(Size) || _X <- lists:seq(1, Size)].
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
DIM A%[10,10] ! in declaration part
.............
Line 710 ⟶ 1,426:
! use a boolean variable or a GOTO label statement
END FOR
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">sequence a
a = rand(repeat(repeat(20, 10), 10))
 
Line 730 ⟶ 1,446:
exit
end if
end for</langsyntaxhighlight>
<code>exit</code> only breaks out of the innermost loop. A better way to do this would be a procedure.
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
//Nigel Galloway: November 10th., 2017
let n = System.Random()
let g = Array2D.init 8 8 (fun _ _ -> 1+n.Next()%20)
Array2D.iter (fun n -> printf "%d " n) g; printfn ""
g |> Seq.cast<int> |> Seq.takeWhile(fun n->n<20) |> Seq.iter (fun n -> printf "%d " n)
</syntaxhighlight>
{{out}}
<pre>
3 7 5 8 7 5 12 14 6 10 7 8 4 8 10 2 12 16 9 19 14 10 1 1 14 2 8 18 1 1 6 19 5 16 15 16 11 19 19 17 3 9 9 15 14 12 20 18 14 8 5 12 20 14 5 14 7 5 15 13 5 15 14 13
3 7 5 8 7 5 12 14 6 10 7 8 4 8 10 2 12 16 9 19 14 10 1 1 14 2 8 18 1 1 6 19 5 16 15 16 11 19 19 17 3 9 9 15 14 12
</pre>
 
=={{header|Factor}}==
Whenever you need to break out of iteration early in Factor, you almost always want to use <code>find</code>. <code>find</code> is a tail-recursive combinator that searches a sequence. Its base case is satisfied when its predicate quotation returns <code>t</code>.
<syntaxhighlight lang="factor">USING: io kernel math.ranges prettyprint random sequences ;
 
10 [ 20 [ 20 [1,b] random ] replicate ] replicate ! make a table of random values
[ [ dup pprint bl 20 = ] find nl drop ] find 2drop ! print values until 20 is found</syntaxhighlight>
 
Alternatively, calling <code>return</code> from inside a <code>with-return</code> quotation allows one to break out of the quotation. This is similar to the way other languages do things: with an explicit break. This is less elegant in Factor because it introduces an additional quotation and involves continuations when they aren't strictly necessary (resulting in slower execution than <code>find</code>).
<syntaxhighlight lang="factor">USING: continuations io kernel math.ranges prettyprint random
sequences ;
 
10 [ 20 [ 20 [1,b] random ] replicate ] replicate ! make a table of random values
[
[ [ dup pprint bl 20 = [ return ] when ] each nl ] each ! print values until 20 is found
] with-return drop</syntaxhighlight>
{{out}}
<pre>
19 5 19 14 15 14 17 16 4 11 17 3 19 10 2 1 8 13 2 6
15 7 12 19 3 7 4 10 7 17 6 1 10 15 6 3 18 18 4 11
20
</pre>
 
=={{header|Fantom}}==
There is no specific way to break out of nested loops (such as a labelled break, or goto). Instead, we can use exceptions and a try-catch block.
<langsyntaxhighlight lang="fantom">class Main
{
public static Void main ()
Line 768 ⟶ 1,520:
echo ("No 20")
}
}</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">include random.fs
 
10 constant X
Line 788 ⟶ 1,540:
20 = if unloop unloop exit then
loop
loop ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|77 and later}}
<langsyntaxhighlight lang="fortran"> PROGRAM LOOPNESTED
INTEGER A, I, J, RNDINT
 
Line 867 ⟶ 1,619:
ENDIF
RETURN
END</langsyntaxhighlight>
{{out|Sample output}}
<pre>A[ 1][ 1] is 2
Line 886 ⟶ 1,638:
{{works with|Fortran|90 and later}}
Here the special feature is that later Fortran allows loops to be labelled (with "outer" in this example) on their first and last statements. Any EXIT or CYCLE statements can then mention the appropriate label so as to be clear just which loop is involved, otherwise the assumption is the innermost loop only. And no "GO TO" statements need appear.
<langsyntaxhighlight lang="fortran">program Example
implicit none
 
Line 904 ⟶ 1,656:
end do outer
end program Example</langsyntaxhighlight>
{{out|Sample output}}
<pre>
14 2 1 11 8 1 14 11 3 15
7 15 16 6 7 17 3 20
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Randomize
Dim a(1 To 20, 1 To 20) As Integer
For i As Integer = 1 To 20
For j As Integer = 1 To 20
a(i, j) = Int(Rnd * 20) + 1
Next j
Next i
 
For i As Integer = 1 To 20
For j As Integer = 1 To 20
Print Using "##"; a(i, j);
Print " ";
If a(i, j) = 20 Then Exit For, For '' Exits both for loops
Next j
Print
Next i
 
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
Sample output :
 
{{out}}
<pre>
13 3 16 13 16 11 15 19 10 5 12 7 17 1 6 11 2 19 11 11
12 17 20
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">array = new array[[10,10], {|x,y| random[1,20]}]
 
println["array is:\n" + formatTable[array, "right"] + "\n"]
 
[rows,cols] = array.dimensions[]
 
ROW:
for r = 0 to rows-1
for c = 0 to cols-1
{
print[array@r@c + " " ]
if array@r@c == 20
break ROW
}</syntaxhighlight>
{{out}}
<pre>
array is:
19 1 15 14 10 20 13 4 20 14
12 2 4 16 17 4 1 8 20 18
12 17 2 11 13 14 9 18 4 16
15 14 1 13 16 9 8 10 3 12
14 1 14 5 17 20 5 6 15 3
17 10 6 16 1 2 4 14 2 6
14 7 1 13 7 16 10 3 11 11
5 3 18 15 20 18 16 5 11 7
19 18 4 8 7 18 11 14 2 3
10 17 11 10 20 18 14 20 15 14
 
19 1 15 14 10 20
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
long a(9,9), i, j
BOOL done = NO
 
for i = 0 to 9
for j = 0 to 9
a(i,j) = rnd(20)
next
next
 
for i = 0 to 9
for j = 0 to 9
print a(i,j)
if ( a(i,j) == 20 ) then done = YES : break
next
if ( done ) then break
next
 
HandleEvents
</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=77521a9ffe6bebdfe2e34df8faab5e78 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siArray As New Short[5, 5]
Dim siCount0, siCount1 As Short
Dim bBreak As Boolean
 
For siCount0 = 0 To 4
For siCount1 = 0 To 4
siArray[siCount0, siCount1] = Rand(1, 20)
siArray[siCount0, siCount1] = Rand(1, 20)
Next
Next
 
For siCount0 = 0 To 4
For siCount1 = 0 To 4
If siArray[siCount0, siCount1] = 20 Then
bBreak = True
Break
Endif
Next
If bBreak Then Break
Next
 
Print "Row " & Str(siCount0) & " column " & Str(siCount1) & " = 20"
 
End</syntaxhighlight>
Output:
<pre>
Row 5 column 4 = 20
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># You can't break an outer loop unless you return from the whole function.
n := 40;
a := List([1 .. n], i -> List([1 .. n], j -> Random(1, 20)));;
Line 929 ⟶ 1,799:
end;
 
Find(a, 20);</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 963 ⟶ 1,833:
}
fmt.Printf("\n")
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
{{Trans|Java}}
Solution:
<langsyntaxhighlight lang="groovy">final random = new Random()
def a = []
(0..<10).each {
Line 989 ⟶ 1,859:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 19, 14, 16, 3, 12, 14, 18, 12, 6]
Line 1,005 ⟶ 1,875:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
breakIncl :: (a -> Bool) -> [a] -> [a]
 
breakIncl p = uncurry ((. take 1). (++)). break p
 
taskLLB k = map (breakIncl (==k)). breakIncl (k `elem`)</langsyntaxhighlight>
{{out|Example}}
<syntaxhighlight lang ="haskell">mij :: [[Int]]
*Main> mapM_ (mapM_ print) $ taskLLB 20 [[2,6,17,5,14],[1,9,11,18,10],[13,20,8,7,4],[16,15,19,3,12]]
mij = takeWhile(not.null). unfoldr (Just. splitAt 5) $
[2, 6, 17, 5, 14, 1, 9, 11, 18, 10, 13, 20, 8, 7, 4, 16, 15, 19, 3, 12]
 
*Main> mapM_ (mapM_ print) $ taskLLB 20 mij
2
6
Line 1,027 ⟶ 1,894:
10
13
20</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: n=20, array(n,n)
 
array = NINT( RAN(10,10) )
Line 1,041 ⟶ 1,908:
ENDDO
 
99 END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon use 'break' to exit loops and execute an expression argument. To exit nested loops 'break' is repeated as the expression.
<langsyntaxhighlight Iconlang="icon">procedure main()
 
every !(!(L := list(10)) := list(10)) := ?20 # setup a 2d array of random numbers up to 20
Line 1,054 ⟶ 1,921:
break break write("L[",i,",",j,"]=20")
 
end</langsyntaxhighlight>
<langsyntaxhighlight Iconlang="icon">every x := L[i := 1 to *L,1 to *L[i]] do
if x = 20 then break write("L[",i,",",j,"]=20") # more succinctly
 
every if !!L = 20 then break write("Found !!L=20") # even more so (but looses the values of i and j</langsyntaxhighlight>
 
=={{header|J}}==
In J, using loops is usually a bad idea -- the underlying implementation implements a rich set of highly optimized special case loops. That said, general case loops can be used and can be a good choice when the operations provided by the primitives need to be severely pruned.
In J, using loops is usually a bad idea.
 
HereSo, here's how the problem statement (ignoring the "requirement" for loops) could be solved, without explicit loops (there's a conceptual nested loop and a short circuited search loop implemented within these primitives):
<langsyntaxhighlight Jlang="j">use=: ({.~ # <. 1+i.&20)@:,</langsyntaxhighlight>
Here's how the problem could be solved, using loops:
<langsyntaxhighlight Jlang="j">doubleLoop=:verb define{{
for_row. i.#y do.
for_col. i.1{$y do.
smoutputecho t=.(<row,col) { y
if. 20=t do.'' return. end.
end.
end.
}}</syntaxhighlight>
)</lang>
{{out|Example use}}
<pre> use ?.20 20 $ 21
Line 1,090 ⟶ 1,957:
The first approach is probably a couple thousand times faster than the second.
 
(In real life, good problem definitions might typically involve "use cases" (which are specified in terms of the problem domain, instead in terms of irrelevant details). Of course, "Rosetta Code" is about how concepts would be expressed in different languages. However, even here, tasks which dwell on language-specific issues are probably not a good use of people's time.)
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Random;
 
public class NestedLoopTest {
Line 1,113 ⟶ 1,980:
System.out.println();
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Demonstrates use of <code>break</code> with a label.
Uses <code>print()</code> function from [[Rhino]].
<langsyntaxhighlight lang="javascript">// a "random" 2-D array
var a = [[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1, 20, 16, 5]];
 
Line 1,130 ⟶ 1,997:
}
}
print("done");</langsyntaxhighlight>
 
In a functional idiom of JavaScript, however, we can not use a loop statement, as statements return no value and can not be composed within other functional expressions. Functional JavaScript often replaces a loop with a map or fold. In this case, we can achieve the same task by defining the standard list-processing function '''takeWhile''', which terminates when a condition returns true.
Line 1,138 ⟶ 2,005:
Using the same data as above, and returning the trail of numbers up to twenty from a nested and composable expression:
 
<langsyntaxhighlight JavaScriptlang="javascript">var lst = [[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1,
20, 16, 5]];
 
Line 1,180 ⟶ 2,047:
return a.concat(x);
}).join('\n')
);</langsyntaxhighlight>
 
Output:
<syntaxhighlight lang="javascript">2
<lang JavaScript>2
12
10
Line 1,203 ⟶ 2,070:
8
13
1</langsyntaxhighlight>
 
=={{header|jq}}==
 
jq has a `break` statement for breaking out of nested loops,
and in this entry, it is used in the following function:
 
<syntaxhighlight lang="jq"># Given an m x n matrix,
# produce a stream of the matrix elements (taken row-wise)
# up to but excluding the first occurrence of $max
def stream($max):
. as $matrix
| length as $m
| (.[0] | length) as $n
| label $ok
| {i: range(0;$m), j: range(0;$n)}
| $matrix[.i][.j] as $m
| if $m == $max then break $ok else $m end ;</syntaxhighlight>
 
The nesting above could be made more visually explicit, for example, by using
the equivalent form:
 
range(0;$m) as $i
| range(0;$n) as $j
 
but the previous formulation illustrates a concise alternative.
 
To generate the random matrix, and to accomplish the "pretty-printing"
component of the task, the following function for converting a stream
to an array of arrays is useful:
 
<syntaxhighlight lang="jq"># Create an array of arrays by using the items in the stream, s,
# to create successive rows, each row having at most n items.
def reshape(s; n):
reduce s as $s ({i:0, j:0, matrix: []};
.matrix[.i][.j] = $s
| if .j + 1 == n then .i += 1 | .j = 0
else .j += 1
end)
| .matrix;</syntaxhighlight>
 
Assuming the availability of rand/1 (e.g. as defined below),
we can now readily define functions to create the matrix and pretty-print the
items as required:
<syntaxhighlight lang="jq"># Create an m x n matrix filled with numbers in [1 .. max]
def randomMatrix(m; n; max):
reshape(limit(m * n; rand(max) + 1); n);
 
# Present the matrix up to but excluding the first occurrence of $max
def show($m; $n; $max):
reshape( randomMatrix($m; $n; $max) | stream($max); $n)[] ;
 
# Main program for the problem at hand.
show(20; 4; 20)</syntaxhighlight>
 
{{out}}
 
Assuming proper placement of PRNG functions as defined below, the following invocation:
$ jq -cn -f program.jq --arg seed 17
 
produces:
 
<pre>[1,17,19,12]
[13,8,18,10]
[18,15,3,18]
[11,12,3,10]
[4,8,1,14]
[12,1,10,9]
[3,16,19,13]
[10,12,13]</pre>
 
 
''' PRNG '''
<syntaxhighlight lang="jq"># LCG::Microsoft generates 15-bit integers using the same formula
# as rand() from the Microsoft C Runtime.
# Input: [ count, state, random ]
def next_rand_Microsoft:
.[0] as $count
| ((214013 * .[1]) + 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];
 
# A random integer in [0 ... (n-1)]:
# rand_Microsoft returns an integer in 0 .. 32767
def rand(n): n * (rand_Microsoft($seed|tonumber) / 32768) | trunc;</syntaxhighlight>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* Loops/Nested in Jsish */
Math.srand(0);
var nrows = Math.floor(Math.random() * 4) + 4;
var ncols = Math.floor(Math.random() * 6) + 6;
 
var matrix = new Array(nrows).fill(0).map(function(v, i, a):array { return new Array(ncols).fill(0); } );
 
var i,j;
for (i = 0; i < nrows; i++) for (j = 0; j < ncols; j++) matrix[i][j] = Math.floor(Math.random() * 20) + 1;
 
/* Labelled break point */
outer_loop:
for (i in matrix) {
printf("row %d:", i);
for (j in matrix[i]) {
printf(" %d", matrix[i][j]);
if (matrix[i][j] == 20) {
printf("\n");
break outer_loop;
}
}
printf("\n");
}
puts(matrix);
 
/*
=!EXPECTSTART!=
row 0: 2 18 12 16 14 8 18 15 9 8
row 1: 15 6 8 16 17 12 15 2 10 3
row 2: 11 8 12 20
[ [ 2, 18, 12, 16, 14, 8, 18, 15, 9, 8 ],
[ 15, 6, 8, 16, 17, 12, 15, 2, 10, 3 ],
[ 11, 8, 12, 20, 18, 4, 6, 6, 19, 9 ],
[ 16, 3, 2, 19, 1, 4, 8, 4, 11, 18 ] ]
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u loopsNested.jsi
[PASS] loopsNested.jsi</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
M = [rand(1:20) for i in 1:5, j in 1:10]
R, C = size(M)
Line 1,224 ⟶ 2,223:
end
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,242 ⟶ 2,241:
</pre>
Julia is column ordered, but this program searches in row order to be consistent with the other solutions of this task.
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.random.Random
 
fun main() {
val a = Array(10) { IntArray(10) { Random.nextInt(1..20) } }
println("array:")
for (i in a.indices) println("row $i: ${a[i].contentToString()}")
 
println("search:")
outer@ for (i in a.indices) {
print("row $i:")
for (j in a[i].indices) {
print(" " + a[i][j])
if (a[i][j] == 20) break@outer
}
println()
}
println()
}</syntaxhighlight>
{{out}}
<pre>array:
row 0: [10, 8, 19, 17, 19, 7, 13, 16, 16, 4]
row 1: [6, 2, 6, 1, 11, 10, 2, 8, 1, 14]
row 2: [3, 6, 4, 6, 10, 2, 10, 20, 18, 1]
row 3: [16, 14, 6, 13, 18, 8, 18, 7, 4, 18]
row 4: [14, 10, 13, 11, 2, 17, 16, 19, 1, 1]
row 5: [4, 20, 6, 17, 20, 12, 20, 15, 16, 15]
row 6: [2, 20, 6, 5, 5, 15, 1, 2, 6, 18]
row 7: [14, 6, 8, 10, 12, 8, 12, 3, 14, 10]
row 8: [1, 5, 15, 12, 7, 14, 9, 7, 16, 11]
row 9: [20, 16, 5, 13, 15, 9, 3, 2, 2, 16]
search:
row 0: 10 8 19 17 19 7 13 16 16 4
row 1: 6 2 6 1 11 10 2 8 1 14
row 2: 3 6 4 6 10 2 10 20</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
1) the A.find function gets a value and a unidimensional array,
then retuns the item matching the value else -1
 
{def A.find
{def A.find.r
{lambda {:val :arr :n :i :acc}
{if {> :i :n}
then -1
else {if {= :val {A.get :i :arr}}
then :i
else {A.find.r :val :arr :n {+ :i 1} {A.addlast! :i :acc}}}}}}
{lambda {:val :arr}
{A.find.r :val :arr {- {A.length :arr} 1} 0 {A.new}}}}
-> A.find
 
{def A {A.new {S.serie 0 20}}}
-> A = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
 
{A.find 12 {A}}
-> 12 // the index
{A.find 21 {A}}
-> -1 // not found
 
2) the AA.find function gets a value and a bidimensional array,
then returns the sequence of rows until the row containing the value,
and diplays the row containing the value if it exists else displays "the value was not found".
 
{def AA.find
{def AA.find.r
{lambda {:val :arr :n :i}
{if {> :i :n}
then {br}:val was not found
else {if {not {= {A.find :val {A.get :i :arr}} -1}} // call the A.find function on each row
then {br}:val was found in {A.get :i :arr}
else {br}{A.get :i :arr} {AA.find.r :val :arr :n {+ :i 1}} }}}}
{lambda {:val :arr}
{AA.find.r :val :arr {- {A.length :arr} 1} 0}}}
-> AA.find
 
3) testing
 
3.1) the rn function returns a random integer between 0 and n
{def rn {lambda {:n} {round {* :n {random}}}}}
-> rn
 
3.2) creating a bidimensional array containing random integers between 0 and 20
{def AA {A.new {A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
{A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
{A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
{A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}}}
-> AA = [[9,4,10,14,1],[4,12,7,18,13],[7,13,19,12,11],[18,4,2,14,15]]
 
3.3) calling with a value which can be in the array
{AA.find 12 {AA}}
->
[9,4,10,14,1]
12 was found in [4,12,7,18,13]
 
3.4) calling with a value outside of the array
{AA.find 21 {AA}}
->
[9,4,10,14,1]
[4,12,7,18,13]
[7,13,19,12,11]
[18,4,2,14,15]
21 was not found
</syntaxhighlight>
 
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&values = fn.arrayMake(10)
$i
repeat($[i], 10) {
&array = fn.arrayMake(10)
$j
repeat($[j], 10) {
&array[$j] $= fn.randRange(20) + 1
}
&values[$i] ::= &array
}
 
$row
foreach($[row], &values) {
$ele
foreach($[ele], $row) {
fn.print(\s$ele)
if($ele === 20) {
con.break(2) # Number of loops we want to break out of
}
}
fn.println()
}
 
fn.println()
</syntaxhighlight>
 
{{out}}
<pre>
18 17 9 3 14 7 6 4 13 18
2 14 8 4 11 10 3 13 15 4
19 17 3 10 4 15 13 6 16 9
3 2 4 17 9 19 9 18 1 12
2 18 13 20
</pre>
 
=={{header|Lasso}}==
 
<langsyntaxhighlight Lassolang="lasso">local(a) = array(
array(2, 12, 10, 4),
array(18, 11, 9, 3),
Line 1,265 ⟶ 2,412:
#1 == 20 ? return
}
}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">dim ar(10,10)
for i = 1 to 10
for j = 1 to 10
Line 1,286 ⟶ 2,433:
if flag then exit for
next
print "Completed row ";x;" and column ";y</langsyntaxhighlight>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">-- create two-dimensional array with random numbers
a = []
repeat with i = 1 to 20
a[i] = []
repeat with j = 1 to 20
a[i][j] = random(20)
end repeat
end repeat
 
-- iterate over rows and columns, print value, exit both loops if it's 20
repeat with i = 1 to 20
repeat with j = 1 to 20
v = a[i][j]
put v
if v=20 then exit repeat
end repeat
if v=20 then exit repeat
end repeat</syntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">Section Header
 
+ name := TEST_LOOP_NESTED;
Line 1,323 ⟶ 2,490:
};
'\n'.print;
);</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">repeat with i = 1 to 10
repeat with j = 1 to 10
put random(20) into aNums[i,j]
Line 1,346 ⟶ 2,513:
else
put "20 not found"
end if</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">make "a mdarray [10 10]
 
for [j 1 10] [for [i 1 10] [mdsetitem list :i :j :a (1 + random 20)]]
Line 1,363 ⟶ 2,530:
]
end
until.20</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">t = {}
for i = 1, 20 do
t[i] = {}
Line 1,380 ⟶ 2,547:
end
end
print(exitable())</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
We can use a number as a label, so instead of using "then goto there" we can use "then 1000" if label is 1000.
 
No numeric labels may have only comments in same line.
 
Numeric labels may have 1 to 5 digits, including leading zeros. So 00010 is label 10. Numeric labels have no : after, but if we place one then this isn't fault, because : is a statement separator.
 
In this example we execute nested for two times, using a third for.
 
 
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Dim A(10,10)<<Random(1, 20)
For k=1 to 2 {
For i=0 to 9 {
For j=0 to 9 {
Print A(i,j)
if A(i,j)=20 then goto there
}
}
there:
Print "...ok", k
}
}
Checkit
</syntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">(m,n) := LinearAlgebra:-Dimensions(M):
for i from 1 to m do
for j from 1 to n do
Line 1,391 ⟶ 2,585:
end if;
end do;
end do:</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Do[ Print[m[[i, j]]];
If[m[[i, j]] === 20, Return[]],
{i, 1, Dimensions[m][[1]]},
{j, 1, Dimensions[m][[2]]}]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Loops are considered slow in Matlab and Octave, it is preferable to vectorize the code.
<langsyntaxhighlight Matlablang="matlab"> a = ceil(rand(100,100)*20);
[ix,iy]=find(a==20,1)</langsyntaxhighlight>
A non-vectorized version of the code is shown below in Octave
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">data: apply(matrix, makelist(makelist(random(100), 20), 20))$
 
find_value(a, x) := block(
Line 1,420 ⟶ 2,614:
 
find_value(data, 100);
not found</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
fn scan_Nested arr =
(
Line 1,435 ⟶ 2,629:
)
)
</syntaxhighlight>
</lang>
 
Example:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
testArray = #(#(1,5,2,19),#(11,20,7,2))
scan_nested testArray
Line 1,451 ⟶ 2,645:
OK
 
</syntaxhighlight>
</lang>
 
=={{header|Microsoft Small Basic}}==
<syntaxhighlight lang="smallbasic">For row = 0 To 10
For col = 0 To 10
array[row][col] = Math.GetRandomNumber(20)
EndFor
EndFor
For row = 0 To 10
For col = 0 To 10
TextWindow.WriteLine("row "+row+" col "+col+" value "+array[row][col])
If array[row][col] = 20 Then
Goto exit_for_row
EndIf
EndFor
EndFor
exit_for_row:</syntaxhighlight>
{{out}}
<pre>row 0 col 0 value 11
row 0 col 1 value 19
row 0 col 2 value 19
row 0 col 3 value 1
row 0 col 4 value 20</pre>
 
=={{header|MOO}}==
<langsyntaxhighlight lang="moo">a = make(10, make(10));
for i in [1..10]
for j in [1..10]
Line 1,471 ⟶ 2,687:
s = "";
endfor
player:tell(s);</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">NESTLOOP
;.../loops/nested
;set up the 2D array with random values
Line 1,486 ⟶ 2,702:
FOR I=1:1:K Q:FLAG W ! FOR J=1:1:K WRITE A(I,J),$SELECT(J'=K:", ",1:"") SET FLAG=(A(I,J)=TRIGGER) Q:FLAG
KILL A,I,J,K,FLAG,TRIGGER
QUIT</langsyntaxhighlight>
{{out}}
<pre>USER>D NESTLOOP^ROSETTA
Line 1,495 ⟶ 2,711:
9, 10, 10, 13, 2, 9, 6, 10, 1, 12, 12, 10, 8, 1, 13
7, 14, 12, 9, 14, 3, 20,</pre>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
Loops/Nested in Neko
Tectonics:
nekoc loops-nested.neko
neko loops-nested.neko
*/
 
var random = $loader.loadprim("std@random_new", 0)();
var random_int = $loader.loadprim("std@random_int", 2);
 
var values = $amake(10);
var row = 0;
var col = 0;
 
while row < 10 {
values[row] = $amake(10);
col = 0;
while col < 10 {
values[row][col] = random_int(random, 20) + 1;
col += 1;
}
row += 1;
}
 
/* Look for a 20 */
/*
To break out of nested loops, (without using labels and $goto),
Neko needs the value of the inner loop(s).
The break statement sets the return value of a loop expression.
Without a break, the value of a loop expression is unspecified.
*/
var inner;
row = 0;
while row < 10 {
col = 0;
inner = while col < 10 {
$print("values[", row, "][", col, "] = ", values[row][col], "\n");
if values[row][col] == 20 break true;
col += 1;
}
if $istrue(inner) break;
row += 1;
}</syntaxhighlight>
 
{{out}}
<pre>prompt$ nekoc loops-nested.neko
prompt$ neko loops-nested
values[0][0] = 17
values[0][1] = 1
values[0][2] = 8
values[0][3] = 5
values[0][4] = 18
values[0][5] = 17
values[0][6] = 17
values[0][7] = 19
values[0][8] = 2
values[0][9] = 1
values[1][0] = 11
values[1][1] = 4
values[1][2] = 16
values[1][3] = 11
values[1][4] = 12
values[1][5] = 20</pre>
 
=={{header|Nemerle}}==
{{trans|C#}}
Nemerle can jump out of a named block by invoking the blocks name with an optional return value.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle.Imperative;
Line 1,522 ⟶ 2,803:
}
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 1,552 ⟶ 2,833:
finally
say
end x1</langsyntaxhighlight>
I was somewhat disappointed by the performance of the above program
and started a little performance analysis on solutions of this task
Line 1,575 ⟶ 2,856:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(let (a (array 10 10))
(dotimes (i 10)
(dotimes (j 10)
Line 1,585 ⟶ 2,866:
(print " ")
(if (= 20 (a i j))
(throw))))))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import mathrandom, strutils
 
const arrSizeArrSize = 10
 
var a: array[0..arrSize-1ArrSize, array[0..arrSize-1ArrSize, int]]
var s: string = ""
 
randomize() # differentDifferent results each time this runs.
 
# Initialize using loops on items rather than indexes.
for i in 0 .. arrSize-1:
for jrow in countup(0,arrSize-1)a.mitems:
for item in row.mitems:
a[i][j] = random(20)+1
item = rand(1..20)
 
block outer:
# Loop using indexes.
for i in countup(0,arrSize-1):
for ji in 0 .. arrSize-1<ArrSize:
for j in if a[i][j] 0..< 10ArrSize:
if a[i][j] < 10: s.add("' "')
addf(s, "$#", $a[i][j])
if a[i][j] == 20: break outer
s.add(", break outer")
s.add(", "'\n')
 
s.add("\n")
echo( s)</langsyntaxhighlight>
 
{{out}}
<pre> 9, 16, 3, 18, 4, 17, 2, 16, 7, 6,
1, 6, 1, 11, 9, 8, 12, 7, 19, 8,
13, 16, 4, 5, 2, 20</pre>
 
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 DIM A(20)
20 FOR I=1 TO 20
30 A(I)=RND(20)+1
40 NEXT
50 PRINT "THE FULL LIST:";
60 FOR I=1 TO 20
70 PRINT A(I);
80 NEXT
90 PRINT
100 PRINT "THE FULL LIST UP TO THE FIRST ";"INSTANCE OF 20:";
110 FOR I=1 TO 20
120 PRINT A(I);
130 IF A(I)=20 THEN END
140 NEXT</syntaxhighlight>
 
=={{header|OCaml}}==
Line 1,621 ⟶ 2,920:
In the interactive interpreter:
 
<langsyntaxhighlight lang="ocaml">$ ocaml
 
# Random.self_init();;
Line 1,656 ⟶ 2,955:
15 3 5 19 17 3 1 11 5 2
1 1 6 19 20
- : unit = ()</langsyntaxhighlight>
 
=={{header|Octave}}==
Octave has no way of exiting nested loop; so we need a control variable, or we can use the trick of embedding the loops into a function and use the <tt>return</tt> statement. (The search for "exactly 20" is changed into a search for "almost 20")
<langsyntaxhighlight lang="octave">function search_almost_twenty()
% create a 100x100 matrix...
m = unifrnd(0,20, 100,100);
Line 1,689 ⟶ 2,988:
break;
endif
endfor</langsyntaxhighlight>
 
=={{header|OoRexx}}==
<langsyntaxhighlight lang="oorexx">numbers = .array~new()
do i = 1 to 10
do j = 1 to 10
Line 1,705 ⟶ 3,004:
leave i
end
end</langsyntaxhighlight>
 
=={{header|Oz}}==
We can directly access and use the outer loop's break procedure:
<langsyntaxhighlight lang="oz">declare
fun {CreateMatrix Width Height}
Matrix = {List.make Height}
Line 1,732 ⟶ 3,031:
end
in
{PrintMatrix {CreateMatrix 10 10}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">M=matrix(10,10,i,j,random(20)+1);
for(i=1,10,for(j=1,10,if(M[i,j]==20,break(2))))</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|FreePascal|1.0}}
<langsyntaxhighlight lang="pascal">program LoopNested;
uses SysUtils;
const Ni=10; Nj=20;
Line 1,760 ⟶ 3,059:
end;
loopend:
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my $a = [ map [ map { int(rand(20)) + 1 } 1 .. 10 ], 1 .. 10];
 
Outer:
Line 1,775 ⟶ 3,074:
print "\n";
}
print "\n";</langsyntaxhighlight>
 
=={{header|Perl 6}}==
{{works with|rakudo|2015-09-18}}
<lang perl6>my @a = [ (1..20).roll(10) ] xx *;
 
LINE: for @a -> @line {
for @line -> $elem {
print " $elem";
last LINE if $elem == 20;
}
print "\n";
}
print "\n";</lang>
{{out}}
<pre> 15 6 14 13 14 7 9 16 8 18
7 6 18 11 19 13 12 5 18 8
17 17 9 5 4 8 17 8 3 11
9 20</pre>
 
=={{header|Phix}}==
use an explicit flag
<!--<syntaxhighlight lang="phix">-->
<lang Phix>constant s = sq_rand(repeat(repeat(20,20),20))
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">),</span><span style="color: #000000;">20</span><span style="color: #0000FF;">))</span>
integer found = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to 20 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
for j=1 to 20 do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
printf(1,"%d",s[i][j])
<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;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span>
if s[i][j]=20 then
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">20</span> <span style="color: #008080;">then</span>
found = 1
<span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
exit
<span style="color: #008080;">exit</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,", ")
<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;">", "</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"\n")
<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;">"\n"</span><span style="color: #0000FF;">)</span>
if found then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">found</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>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
alternatively you can use a procedure
<!--<syntaxhighlight lang="phix">-->
<lang Phix>procedure till20()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">till20</span><span style="color: #0000FF;">()</span>
for i=1 to 20 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
for j=1 to 20 do
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
printf(1,"%d",s[i][j])
<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;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span>
if s[i][j]=20 then return end if
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">20</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,", ")
<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;">", "</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"\n")
<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;">"\n"</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
till20()
<span style="color: #000000;">till20</span><span style="color: #0000FF;">()</span>
printf(1,"\n")</lang>
<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;">"\n"</span><span style="color: #0000FF;">)</span>
or even inline assembly to effect a goto
<!--</syntaxhighlight>-->
<lang Phix>for i=1 to 20 do
or a goto
for j=1 to 20 do
<!--<syntaxhighlight lang="phix">-->
printf(1,"%d",s[i][j])
<span style="color: #008080;">procedure</span> <span style="color: #000000;">till20</span><span style="color: #0000FF;">()</span>
if s[i][j]=20 then #ilASM{jmp :%done} end if
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
printf(1,", ")
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20</span> <span style="color: #008080;">do</span>
end for
<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;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span>
printf(1,"\n")
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">20</span> <span style="color: #008080;">then</span> <span style="color: #008080;">goto</span> <span style="color: #0000FF;">:</span><span style="color: #000000;">done</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<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;">", "</span><span style="color: #0000FF;">)</span>
#ilASM{:%done}
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"\n")</lang>
<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;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">::</span><span style="color: #000000;">done</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;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">till20</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
Line 1,851 ⟶ 3,141:
}
echo "\n";
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(for Lst (make (do 10 (link (make (do 10 (link (rand 1 20)))))))
(T
(for N Lst
(printsp N)
(T (= N 20) T) ) ) )</langsyntaxhighlight>
or:
<langsyntaxhighlight PicoLisplang="picolisp">(catch NIL
(for Lst (make (do 10 (link (make (do 10 (link (rand 1 20)))))))
(for N Lst
(printsp N)
(and (= N 20) (throw)) ) ) )</langsyntaxhighlight>
 
=={{header|Pike}}==
 
Pike does not have a generic goto, but break is a special case in that
you can specify labels and break several levels of loop. In practise
this is extremely seldom used in favor of using a state variable or
containing the nest in a function that you <tt>return</tt> from in the
inner loop. However it's there if you want it:
 
<syntaxhighlight lang="text">
int main()
{
// enumerate() normally returns a linearly enumerated array, but
// allows for the forth argument to specify a function that will
// be called and return the value that should be in each cell. We
// create an anonymous function (lambda) that just returns a
// random value.
array a = ({});
for(int i=0; i<20; i++)
a += ({ enumerate( 20, 1, 1, lambda(){return random(20)+1;} ) });
 
// We could use for() and a[x][y] indexing, but foreach is just
// shorter and easier to use even if the 2D-array becomes less
// obvious.
mynestedloops:
foreach(a, array inner_a) {
foreach(inner_a, int value) {
write(value +" ");
if(value == 20)
break mynestedloops;
}
}
write("\n");
}
</syntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii"> declare x(20,20) fixed; /* 16 August 2010. */
x = random()*20 + 1;
loops:
Line 1,876 ⟶ 3,201:
end;
if x(i,j) = 20 then leave;
end;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">; Creating and filling array
Dim Value(10, 5)
For a = 0 To 10
Line 1,895 ⟶ 3,220:
EndIf
Next
Next</langsyntaxhighlight>
 
=={{header|Python}}==
Python has only inner loop breaks. The normal way to solve this problem in Python is to move the code in a function, and use return:
<langsyntaxhighlight lang="python">from random import randint
 
def do_scan(mat):
Line 1,912 ⟶ 3,237:
 
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)</langsyntaxhighlight>
The , after print element suppresses printing a line break. The code needs some minor changes for Python 3.
 
Two more solutions around this problem, the first uses exception handling:
<langsyntaxhighlight lang="python">from random import randint
 
class Found20(Exception):
Line 1,931 ⟶ 3,256:
print
except Found20:
print</langsyntaxhighlight>
The second uses a flag variable:
<langsyntaxhighlight lang="python">from random import randint
 
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
Line 1,946 ⟶ 3,271:
print
if found20:
break</langsyntaxhighlight>
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
<lang Qi>
(define random-list
0 -> []
Line 1,965 ⟶ 3,290:
 
(array->list 20 (random-array 10 10))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> []
5 times
[ []
5 times [ 20 random 1+ join ]
nested join ]
dup say "Array contains:" cr
witheach
[ witheach
[ echo sp ]
cr ]
cr
say "Array up to item = 20:" cr
witheach
[ false swap
witheach
[ dup 20 = iff
[ drop not conclude ]
else
[ echo sp ] ]
iff conclude
else cr ]</syntaxhighlight>
 
{{out}}
 
<pre>Array contains:
16 9 10 11 6
2 10 14 12 20
19 4 4 3 18
15 20 10 7 3
10 19 14 10 7
 
Array up to item = 20:
16 9 10 11 6
2 10 14 12
</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">m <- 10
n <- 10
mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m); mat
Line 1,989 ⟶ 3,353:
break
}
}</langsyntaxhighlight>
 
or
 
<syntaxhighlight lang="r">
<lang R>
m <- 10; n <- 10; mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m);
x<-which(mat==20,arr.ind=TRUE,useNames=FALSE)
Line 1,999 ⟶ 3,363:
for(i in mat[1:x[1,1]-1,]) print(i)
for(i in mat[x[1,1],1:x[1,2]]) print(i)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (scan xss)
Line 2,015 ⟶ 3,379:
(+ (random 20) 1))))
 
(scan matrix)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-18}}
<syntaxhighlight lang="raku" line>my @a = [ (1..20).roll(10) ] xx *;
 
LINE: for @a -> @line {
for @line -> $elem {
print " $elem";
last LINE if $elem == 20;
}
print "\n";
}
print "\n";</syntaxhighlight>
{{out}}
<pre> 15 6 14 13 14 7 9 16 8 18
7 6 18 11 19 13 12 5 18 8
17 17 9 5 4 8 17 8 3 11
9 20</pre>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Loop/Nested"
Author: oofoe
Date: 2010-01-05
URL: http://rosettacode.org/wiki/Loop/Nested
]
Line 2,057 ⟶ 3,438:
]
]
prin crlf</langsyntaxhighlight>
{{out}}
<pre>Loop break using state variable:
Line 2,076 ⟶ 3,457:
02 13 14 14 15 01 10 07 17 03
07 17 20</pre>
 
=={{header|ReScript}}==
<syntaxhighlight lang="rescript">let m = []
 
for _ in 0 to 9 {
let n = []
for _ in 0 to 9 {
let _ = Js.Array2.push(n, 1 + Js.Math.random_int(0, 20))
}
let _ = Js.Array2.push(m, n)
}
 
try {
for i in 0 to 9 {
for j in 0 to 9 {
Js.log(m[i][j])
if m[i][j] == 20 { raise(Exit) }
}
}
} catch {
| Exit => Js.log("stop")
}</syntaxhighlight>
 
=={{header|REXX}}==
Line 2,081 ⟶ 3,484:
to contain the target (20), it's possible to not find the target.
<br>Code was added to this REXX program to reflect that possibility and issue an appropriate message (whether the target was found or not).
<langsyntaxhighlight lang="rexx">/*REXX program loops through a 2two-dimensional array to looksearch for a '20' (twenty). */
parse arg rows cols targ . /*obtain optional argsarguments from C.L.the CL*/
if rows=='' | rows=='",'" then rows=60 /*Rows not specified? Use Then use default*/
if cols=='' | cols=='",'" then cols=10 /*Cols " " " " " */
if targ=='' | targ=='",'" then targ=20 /*Targ " " " " " */
w=max(length(rows), length(cols), length(targ)) /*W: used for formatting the output. */
not= 'not' /* [↓] construct the 2-dim2─dimension array.*/
do row=1 for rows /*ROW is the 1st dimension of the array. */
do col=1 for cols /*2ndCOL " " 2nd " " " " */
@.row.col=random(1, targ) /*generatecreate some positive random numbersintegers. */
end /*row*/
end /*col*/
 
/*═════════════════════════════════════now, search for the target {20}.*/
do r=1 for rows /* ◄───────────────── now, search for the target {20}.*/
do c=1 for cols
say left('@.'r"."c, 3+w+w) '=' right(@.r.c, w) /*displayshow an array element.*/
if @.r.c==targ then do; not=; leave r; end /*found ?the targ number?*/
end /*c*/
end /*r*/
 
say right( space( 'Target' not '"found:'" ) targ, 33, '─')
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out}}'''output''' &nbsp; when using the defaultsdefault inputs:
<pre>
@.1.1 = 19
Line 2,128 ⟶ 3,531:
─────────────────Found target: 20
</pre>
{{out}}'''output''' &nbsp; when using the input of: &nbsp; <tt> 2 &nbsp; 2 </tt>
<pre>
@.1.1 = 14
Line 2,138 ⟶ 3,541:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
size = 5
array = newlist(size,size)
Line 2,150 ⟶ 3,553:
for col = 1 to size
see "row " + row + " col " + col + "value : " + array[row][col] + nl
if array[row][col] = 20 exit for row ok
next
next
Line 2,162 ⟶ 3,565:
next
return aList
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,191 ⟶ 3,594:
row 5 col 5 value : 6
</pre>
 
=={{header|RPL}}==
As there is no <code>BREAK</code> instruction in RPL, premature loop exit is usually made by forcing the loop variable to its end value. Depending on the way exit is required and on the need for code optimization within the loop, there are several ways to implement such a break feature. The following one is based on two <code>FOR..NEXT</code> loops:
{ 10 10 } 0 CON
1 10 '''FOR''' j
1 10 '''FOR''' k
j k 2 →LIST RAND 20 * CEIL PUT
'''NEXT'''
''' NEXT'''
DROP 1 CF
1 10 '''FOR''' j
1 10 '''FOR''' k
DUP j k 2 →LIST GET
DUP 1 DISP
'''IF''' 20 == '''THEN''' 1 SF '''END'''
1 FC? 1 10 IFTE '''STEP'''
1 FC? 1 10 IFTE '''STEP'''
We could also only use a <code>WHILE..REPEAT</code> loop, scanning the matrix line by line, but there is no nested loop anymore:
≪ 46 → done
≪ { 10 10 } 0 CON
{ 1 1 }
'''DO'''
RAND 20 * CEIL PUTI
'''UNTIL''' done FS? '''END'''
'''DO'''
GETI DUP 1 DISP
'''UNTIL''' 20 == done FS? OR '''END'''
≫ ≫
The <code>done</code> constant is the number of the system flag that becomes set when the last element of the matrix is written. The above value is for HP-28 versions; HP-48 users must change it to -64.
 
=={{header|Ruby}}==
As the break command only jumps out of the innermost loop,
this task requires Ruby's <code>catch/throw</code> functionality.
<syntaxhighlight lang="ruby">ary = (1..20).to_a.shuffle.each_slice(4).to_a
<lang ruby>
ary = (1..20).to_a.shuffle.each_slice(4).to_a
p ary
 
Line 2,209 ⟶ 3,642:
end
 
puts "done"</langsyntaxhighlight>
{{out}}
<pre>[[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1, 20, 16, 5]]
Line 2,217 ⟶ 3,650:
6 19 8 13 ,
1 20 done</pre>
 
However, for-loops are not very popular. This is more idiomatic ruby, which avoids loops and breaking out of them:
<syntaxhighlight lang ="ruby">p slices = ([*1..20).to_a].shuffle.each_slice(4)
 
slices.any? do |slice|
puts
slice.any? do |element|
slice.any? do puts |element|
print "#{element} "
element == 20
end
end </lang>
puts "done"</syntaxhighlight>
{{out}}
<pre>
#<Enumerator: [121, 144, 59, 1613, 315, 1810, 153, 85, 414, 1917, 918, 78, 2, 12, 6, 1119, 20, 1311, 107, 1, 1716]:each_slice(4)>
 
12
1 4 9 13
14
15 10 3 5
5
14 17 18 8
16
2 12 6 19
3
20 done
18
15
8
4
19
9
7
2
6
11
20
</pre>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim a(10,10)
cls
for row = 1 TO 10
Line 2,263 ⟶ 3,689:
next row
[end]
print "At row:";row;" col:";col</langsyntaxhighlight>
 
 
=={{header|Rust}}==
{{libheader|rand}}
<lang rust>use rand::Rng;
<syntaxhighlight lang="rust">use rand::Rng;
 
extern crate rand;
Line 2,286 ⟶ 3,712:
if item == 20 { break 'outer }
}
println!("");
}
}</langsyntaxhighlight>
{{out}}
<pre> 5 3 8 18 13 2 5 13 6 17
Line 2,294 ⟶ 3,720:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
a:ARRAY2{INT} := #(10,10);
Line 2,317 ⟶ 3,743:
end;
end;
end;</langsyntaxhighlight>
 
=={{header|S-BASIC}}==
S-BASIC doesn't have a BREAK or EXIT statement for early termination of a loop, so the most straight-forward approach is to jump out using a GOTO. But since S-BASIC doesn't allow GOTOs from a FOR..NEXT loop, we have to use WHILE..DO instead.
<syntaxhighlight lang="basic">
$constant ROWS = 10
$constant COLUMNS = 10
$constant MAXVAL = 20
 
var i, j = integer
dim integer table(ROWS, COLUMNS)
 
rem - populate table using nested FOR..NEXT loops
 
for i=1 to ROWS
for j=1 to COLUMNS
table(i, j) = int(rnd(1) * MAXVAL) + 1
next j
next i
 
rem - show results using nested WHILE..DO loops
 
i = 1
while i <= ROWS do
begin
j = 1
while j <= COLUMNS do
begin
print using "## "; table(i, j);
if table(i, j) = MAXVAL then goto 0done
j = j + 1
end
print
i = i + 1
end
 
comment
Although S-BASIC allows alphanumeric line numbers as the target
of a GOTO or GOSUB statement, the first "digit" must in fact be
a number, as shown here.
end
 
0done if i > ROWS then print "target value"; MAXVAL; " not found!"
 
end
</syntaxhighlight>
The use of GOTO, while convenient, is at odds with S-BASIC's structured programming ethos. Adding a boolean flag to the inner loop allows us to avoid the GOTO. Although S-BASIC has no explicit boolean variable type, integers, real numbers, characters, and strings can all be used as boolean variables. For integers, 0 is false and -1 is true. For real variables, 0 is false and any non-zero value is true. For characters, 'T', 't', 'Y', and 'y' are evaluated as true, while 'F', 'f', 'N', and 'n' are evaluated as false. Strings follow the same rule, with only the first character considered.
<syntaxhighlight lang="basic">
$constant ROWS = 10
$constant COLUMNS = 10
$constant TOPVAL = 20
$constant TRUE = FFFFH
$constant FALSE = 0H
 
var i, j, done = integer
dim integer table(ROWS, COLUMNS)
 
rem - populate table using nested FOR..NEXT loops
 
for i=1 to ROWS
for j=1 to COLUMNS
table(i, j) = int(rnd(1) * TOPVAL) + 1
next j
next i
 
rem - show results using nested WHILE..DO loops
 
i = 1
done = FALSE
while i <= ROWS and not done do
begin
j = 1
while j <= COLUMNS and not done do
begin
print using "## "; table(i, j);
if table(i, j) = TOPVAL then done = TRUE
j = j + 1
end
print
i = i + 1
end
 
if i > ROWS then print "Target value of"; TOPVAL; " not found!"
 
end
</syntaxhighlight>
{{out}}
The output is the same for both programs.
<pre>
1 2 7 20
</pre>
 
=={{header|Scala}}==
In Scala there is no build-in 'break' keyword. That functionality comes from a library.
<langsyntaxhighlight lang="scala">import scala.util.control.Breaks._
val a=Array.fill(5,4)(scala.util.Random.nextInt(21))
println(a map (_.mkString("[", ", ", "]")) mkString "\n")
Line 2,329 ⟶ 3,845:
if (x==20) break
}
}</langsyntaxhighlight>
{{out}}
<pre>[14, 16, 5, 7]
Line 2,347 ⟶ 3,863:
=={{header|Scheme}}==
Using call/cc:
<langsyntaxhighlight lang="scheme">(call-with-current-continuation
(lambda (return)
(for-each (lambda (a)
Line 2,358 ⟶ 3,874:
a)
(newline))
array)))</langsyntaxhighlight>
Using tail-call:
<langsyntaxhighlight lang="scheme">(let loop ((a array))
(if (pair? a)
(let loop2 ((b (car a)))
Line 2,370 ⟶ 3,886:
(else
(display " ")(display (car b))
(loop2 (cdr b)))))))</langsyntaxhighlight>
 
=={{header|Scilab}}==
{{works with|Scilab|5.5.1}}
<syntaxhighlight lang="text">ni=3;nj=4
t=int(rand(ni,nj)*20)+1
for i=1:ni
Line 2,383 ⟶ 3,899:
printf("\n")
if t(i,j)==11 then break; end
end</langsyntaxhighlight>
{{out}}
<pre> 5 18 19 8
Line 2,390 ⟶ 3,906:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,417 ⟶ 3,933:
catch FOUND20: writeln;
end block;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,427 ⟶ 3,943:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = 10.of{ 10.of{ 20.rand.intirand + 1 } };
 
for (row in arr) { |row|
for (num in row) { |num|
"%3d".printf(num);
num == 20 && goto :OUT;
}
print "\n";
} @:OUT;
 
print "\n";</langsyntaxhighlight>
{{out}}
<pre> 9 17 14 17 17 7 1 3 9 18
Line 2,454 ⟶ 3,970:
it looks a bit wierd, but here is: loopWithExit
 
<langsyntaxhighlight lang="smalltalk">|i|
 
i := 1.
Line 2,461 ⟶ 3,977:
i == 5 ifTrue:[ exit value:'stopped' ].
i := i + 1.
] loopWithExit</langsyntaxhighlight>
these can also be nested, and exited from the inner loop:
<langsyntaxhighlight lang="smalltalk">|i|
 
i := 1.
Line 2,477 ⟶ 3,993:
] loopWithExit.
i := i + 1
] loopWithExit</langsyntaxhighlight>
in case your smalltalk does not have it, here's the definition:
<langsyntaxhighlight lang="smalltalk">!Block methodsFor:'looping'!
loopWithExit
"the receiver must be a block of one argument. It is evaluated in a loop forever,
Line 2,488 ⟶ 4,004:
 
exitBlock := [:exitValue | ^ exitValue].
[true] whileTrue:[ self value:exitBlock ]</langsyntaxhighlight>
in the same spirit, exits could be added to many other loop constructs. However, this is really only very rarely needed in Smalltalk, because a ^(return) out of a block returns from the enclosing method which usually used to exit early from search utility methods.
 
There is also valueWithExit, which can be used to get out of a block early and provide an alternative value. Using that, the tasks solution is:
<langsyntaxhighlight lang="smalltalk">|v result|
 
v := 1 to:20 collect:[:i |
Line 2,515 ⟶ 4,031:
] ifFalse:[
'20 found at ' print. result printCR
]</langsyntaxhighlight>
{{out}}
<pre>19
Line 2,530 ⟶ 4,046:
 
The following code implements a BiArray class with a method that allows iteration over the elements (by columns and then by rows) and execution of a block if a condition is true.
<langsyntaxhighlight lang="smalltalk">"this simple implementation of a bidimensional array
lacks controls over the indexes, but has a way of iterating
over array's elements, from left to right and top to bottom"
Line 2,578 ⟶ 4,094:
"loop searching for 20; each block gets the element passed as argument"
biarr whileTrue: [ :v | v ~= 20 ]
do: [ :v | v displayNl ]</langsyntaxhighlight>
 
=={{header|SPL}}==
<syntaxhighlight lang="spl">'fill array
mx,my = 30
> y, 1..my
> x, 1..mx
a[x,y] = #.rnd(20)+1
<
<
'scan array
> y, 1..my
> x, 1..mx
#.output("x=",x,", y=",y, ", a=",a[x,y])
<< a[x,y] = 20
<
<< x!>mx
<</syntaxhighlight>
{{out}}
<pre>
x=1, y=1, a=7
x=2, y=1, a=7
x=3, y=1, a=19
x=4, y=1, a=1
x=5, y=1, a=20
</pre>
 
=={{header|Stata}}==
In Stata macro language, one can only break the innermost loop, with '''[https://www.stata.com/help.cgi?continue continue, break]'''. There are several ways to cope with this.
 
First, build the matrix:
 
<syntaxhighlight lang="stata">matrix a=J(20,20,0)
forv i=1/20 {
forv j=1/20 {
matrix a[`i',`j']=runiformint(1,20)
}
}</syntaxhighlight>
 
Use nested '''[https://www.stata.com/help.cgi?forvalues forvalues]'''. If 20 is found, set a flag and break the inner loop. In the outer loop, check the flag and break the outer loop if 20 was found.
 
<syntaxhighlight lang="stata">local q 0
forv i=1/20 {
forv j=1/20 {
display "check `i',`j'"
if el("a",`i',`j')==20 {
display "found at `i',`j'"
local q 1
continue, break
}
}
if `q' continue, break
}
if !`q' {
display "not found"
}</syntaxhighlight>
 
Use nested '''[https://www.stata.com/help.cgi?while while]''' loops, and check both the loop indices and a flag. One could also use an inner forvalue loop together with an outer while loop.
 
<syntaxhighlight lang="stata">local q 0
local i=1
while !`q' & `i'<=20 {
local j=1
while !`q' & `j'<=20 {
display "check `i',`j'"
if el("a",`i',`j')==20 {
display "found at `i',`j'"
local q 1
}
local ++j
}
local ++i
}
if !`q' {
display "not found"
}</syntaxhighlight>
 
Use the exit/capture exception mechanism: '''[https://www.stata.com/help.cgi?exit_program exit]''' tos throw an exception, and '''[https://www.stata.com/help.cgi?capture capture]''' to catch it. Since this catches all exception, you have then to check the value of '''[https://www.stata.com/help.cgi?_variables _rc]'''.
 
<syntaxhighlight lang="stata">capture {
forv i=1/20 {
forv j=1/20 {
display "check `i',`j'"
if el("a",`i',`j')==20 {
display "found at `i',`j'"
exit -1
}
}
}
}
if _rc==-1 {
// value was found
}
else if _rc==0 {
display "not found"
}
else exit _rc</syntaxhighlight>
 
=== Mata ===
In Mata, the situation is simpler: one may '''[https://www.stata.com/help.cgi?m2_return return]''' from a program without resort to exceptions, or use the '''[https://www.stata.com/help.cgi?m2_goto goto]''' statement. It's still possible to use '''[https://www.stata.com/help.cgi?m2_break break]''' and flags though.
 
<syntaxhighlight lang="stata">function findval1(a,x,i0,j0) {
n=rows(a)
p=cols(a)
for (i=1; i<=n; i++) {
for (j=1; j<=p; j++) {
if (a[i,j]==x) {
i0=i
j0=j
return(1)
}
}
}
return(0)
}
 
function findval2(a,x,i0,j0) {
n=rows(a)
p=cols(a)
q=0
for (i=1; i<=n; i++) {
for (j=1; j<=p; j++) {
if (a[i,j]==x) {
i0=i
j0=j
q=1
goto END
}
}
}
END:
return(q)
}
 
function findval3(a,x,i0,j0) {
n=rows(a)
p=cols(a)
q=0
for (i=1; i<=n; i++) {
for (j=1; j<=p; j++) {
if (a[i,j]==x) {
i0=i
j0=j
q=1
break
}
}
if (q) {
break
}
}
return(q)
}</syntaxhighlight>
 
Then with any of these functions, the return value indicates whether x has been found in a, and i,j are the indices where it has been found.
 
<syntaxhighlight lang="stata">a=st_matrix("a")
findval1(a,20,i=.,j=.)
findval2(a,20,i=.,j=.)
findval3(a,20,i=.,j=.)</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">let array = [[2, 12, 10, 4], [18, 11, 20, 2]]
 
loop: for row in array {
Line 2,588 ⟶ 4,265:
}
}
print("done")</langsyntaxhighlight>
{{out}}
<pre> 2
Line 2,599 ⟶ 4,276:
done
</pre>
 
=={{header|Tailspin}}==
In Tailspin you break processing by simply not sending a value on in the chain.
<syntaxhighlight lang="tailspin">
sink find20
def a: $;
1 -> #
when <..$a::length> do def i: $;
'$#10;' -> !OUT::write
1 -> \(
when <$a($i)::length~..> do $i + 1 !
otherwise def j: $;
def val: $a($i;$j);
' $val;' -> !OUT::write
$val -> \(<~=20> $j + 1 ! \) -> #
\) -> #
end find20
 
[1..10 -> [1..10 -> 20 -> SYS::randomInt -> $ + 1]] -> !find20
</syntaxhighlight>
{{out}}
<pre>
 
3 4 2 10 10 10 2 16 9 14
10 2 8 7 19 13 9 9 2 6
5 8 11 18 14 5 3 1 7 19
18 18 16 3 1 19 19 8 6 6
18 9 17 16 13 16 12 15 4 2
12 20</pre>
 
=={{header|Tcl}}==
Tcl only supports single-level breaks; exiting more deeply nested looping requires the use of exceptions, which are considerably more verbose before Tcl 8.6.
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">set ary [subst [lrepeat 10 [lrepeat 5 {[expr int(rand()*20+1)]}]]]
 
try {
Line 2,616 ⟶ 4,322:
}
} trap MULTIBREAK {} {}
puts " done"</langsyntaxhighlight>
{{out}}
<pre> 12 13 14 13 15,
Line 2,626 ⟶ 4,332:
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti83b">PROGRAM:LOOP
(A,B)→dim([C])
For(I,1,A)
Line 2,643 ⟶ 4,349:
End
 
3→A:4→B:prgmLOOP</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
The <code>Stop</code> statement exits the containing ''program''.
<langsyntaxhighlight lang="ti89b">Prgm
Local mat,i,j
© randMat(5, 5) exists but returns -9 to 9 rather than 1 to 20
Line 2,668 ⟶ 4,374:
EndFor
EndFor
EndPrgm</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
LOOP
row=""
Line 2,683 ⟶ 4,389:
ENDLOOP
PRINT row
ENDLOOP</langsyntaxhighlight>
{{out}}
<pre>
Line 2,695 ⟶ 4,401:
{{works with|Bash}}
Bash doesn't have two-dimentional arrays, so we fake it for this example
<langsyntaxhighlight lang="bash">size=10
 
for ((i=0;i<size;i++)); do
Line 2,713 ⟶ 4,419:
echo
done
echo</langsyntaxhighlight>
{{out|Example output}}
<pre> 7 5 4 6 4 5 2 15 10 7
15 4 14 9 10 14 14 3 3 5
14 20 </pre>
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">void main() {
int[,] a = new int[10, 10];
bool broken = false;
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
a[i, j] = Random.int_range(0, 21) % 20 + 1;
 
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
stdout.printf(" %d", a[i, j]);
if (a[i, j] == 20) {
broken = true;
break;
}
}
stdout.printf("\n");
if (broken) break;
}
}</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Public Sub LoopsNested()
Dim a(1 To 10, 1 To 10) As Integer
Randomize
For i = 1 To 10
For j = 1 To 10
a(i, j) = Int(20 * Rnd) + 1
Next j
Next i
For i = 1 To 10
For j = 1 To 10
If a(i, j) <> 20 Then
Debug.Print a(i, j),
Else
i = 10 'Upperbound iterator outerloop
Exit For 'Exit For exits only innerloop
End If
Next j
Debug.Print
Next i
End Sub</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
VB.NET doesn't have labelled loops, but the Exit statement discriminates between different types of block, allowing for several workarounds other than using a goto.
 
The set-up code:
<syntaxhighlight lang="vbnet">Module Program
Sub Main()
Const ROWS = 10
Const COLS = 10
 
' Initialize with seed 0 to get deterministic output (may vary across .NET versions, though).
Dim rand As New Random(0)
 
' VB uses max index array declarations
Dim nums(ROWS - 1, COLS - 1) As Integer
 
For r = 0 To ROWS - 1
For c = 0 To COLS - 1
nums(r, c) = rand.Next(0, 21) ' Upper bound is exclusive.
Next
Next
 
' MISSING IMPLEMENTATION
End Sub
End Module</syntaxhighlight>
 
'''Implementations:'''
 
Perhaps the simplest solution is to use a goto.
<syntaxhighlight lang="vbnet"> For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Dim val = nums(r, c)
Console.WriteLine(val)
If val = 20 Then GoTo BREAK
Next
Next
BREAK:</syntaxhighlight>
 
If, ''for some reason'', a goto is undesirable, an alternative would be to exit a dummy outer block (in this case a single-iteration Do loop).
<syntaxhighlight lang="vbnet"> Do
For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Dim val = nums(r, c)
Console.WriteLine(val)
If val = 20 Then Exit Do
Next
Next
Loop While False</syntaxhighlight>
 
Either For loop can also be converted to a different type of loop.
<syntaxhighlight lang="vbnet"> For r = 0 To ROWS - 1
Dim c = 0
Do While c <= COLS - 1
Dim val = nums(r, c)
Console.WriteLine(val)
If val = 20 Then Exit For
c += 1
Loop
Next</syntaxhighlight>
 
The search can also be factored out to a separate method
<syntaxhighlight lang="vbnet"> Sub Find20Impl(arr As Integer(,))
For r = 0 To arr.GetLength(0) - 1
For c = 0 To arr.GetLength(1) - 1
Dim val = arr(r, c)
Console.WriteLine(val)
If val = 20 Then Exit Sub
'If val = 20 Then Return ' Equivalent to above.
Next
Next
End Sub</syntaxhighlight>
 
and called from Main():
<syntaxhighlight lang="vbnet"> Find20Impl(nums)</syntaxhighlight>
 
A translation of the VBA above, that sets the iteration variable of the outer For loop to an out-of-range value and exits the inner loop regularly.
<syntaxhighlight lang="vbnet"> For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Dim val = nums(r, c)
Console.WriteLine(val)
If val = 20 Then
r = ROWS
Exit For
End If
Next
Next</syntaxhighlight>
 
Similarly, a flag variable can be checked by the outer loop.
<syntaxhighlight lang="vbnet"> Dim done = False
For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Dim val = nums(r, c)
Console.WriteLine(val)
If val = 20 Then
done = True
Exit For
End If
Next
If done Then Exit For
Next</syntaxhighlight>
 
{{out}}
<pre>15
17
16
11
4
11
19
9
20</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import rand
import rand.seed
 
fn main() {
rand.seed(seed.time_seed_array(2))
mut values := [][]int{len:10, init: []int{len:10}}
for i in 0..values.len{
for j in 0..values[0].len {
values[i][j] = rand.intn(20) or {19} +1
}
}
outerloop:
for i,row in values {
println('${i:3})')
for value in row {
print(' ${value:3}')
if value==20{
break outerloop
}
}
println('')
}
}</syntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
Wren doesn't have ''goto'' or ''break label'' so to break out of nested loops you need to use a flag (''found'' in the code below).
<syntaxhighlight lang="wren">import "random" for Random
import "./fmt" for Fmt
 
var rand = Random.new()
 
var a = List.filled(20, null)
for (i in 0..19) {
a[i] = List.filled(20, 0)
for (j in 0..19) a[i][j] = rand.int(1, 21)
}
 
var found = false
for (i in 0..19) {
for (j in 0..19) {
Fmt.write("$4d", a[i][j])
if (a[i][j] == 20) {
found = true
break
}
}
System.print()
if (found) break
}</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
8 5 4 9 5 7 13 8 8 13 17 10 9 4 8 14 16 5 5 9
11 18 16 9 6 17 14 5 10 13 15 8 2 6 18 20
</pre>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
Break out of nested loops by means of an additional variable.
<syntaxhighlight lang="xbasic">
PROGRAM "loopsnested"
 
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()
DIM array%[10, 10]
XstGetSystemTime (@msec)
SRand(INT(msec) MOD 32768)
FOR row% = 0 TO 10
FOR col% = 0 TO 10
array%[row%, col%] = INT(Rand() / 32768.0 * 20.0) + 1
NEXT col%
NEXT row%
 
isFound% = $$FALSE
FOR row% = 0 TO 10
PRINT "Row:"; row%
FOR col% = 0 TO 10
PRINT " Col:"; col%; ", value:"; array%[row%, col%]
IF array%[row%, col%] = 20 THEN
isFound% = $$TRUE
EXIT FOR
END IF
NEXT col%
IFT isFound% THEN
EXIT FOR
END IF
NEXT row%
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>
Row: 0
Col: 0, value: 1
Col: 1, value: 6
Col: 2, value: 15
Col: 3, value: 19
Col: 4, value: 6
Col: 5, value: 7
Col: 6, value: 19
Col: 7, value: 8
Col: 8, value: 11
Col: 9, value: 9
Col: 10, value: 15
Row: 1
Col: 0, value: 3
Col: 1, value: 7
Col: 2, value: 18
Col: 3, value: 1
Col: 4, value: 7
Col: 5, value: 8
Col: 6, value: 9
Col: 7, value: 14
Col: 8, value: 4
Col: 9, value: 20
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def Size=10;
 
Line 2,745 ⟶ 4,747:
[Fill(Array);
Nest(Array);
]</langsyntaxhighlight>
 
=={{header|zkl}}==
Using nested lists to simulate a 5x5 array. No breakbreak so an exception is used to long jump out of the loop (just 'cause, a state var could also be used).
<langsyntaxhighlight lang="zkl">const N=5;
var rows=(0).pump(N,List, (0).pump.fp(N,List,(1).random.fpM("1-",21)) );
try{
Line 2,759 ⟶ 4,761:
}
println("Not found");
}catch(Generic){}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,767 ⟶ 4,769:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 DIM a(10,10)
20 FOR i=1 TO 10: FOR j=1 TO 10
30 LET a(i,j)=INT (RND*20)+1
Line 2,778 ⟶ 4,780:
100 IF b=0 THEN PRINT
110 NEXT i
120 STOP </langsyntaxhighlight>
{{out|Example output}}
<pre>
Line 2,788 ⟶ 4,790:
 
{{omit from|GUISS|No loops or nesting, and we can't read our values}}
{{omit from|PL/0|No arrays}}
{{omit from|Tiny BASIC|No arrays}}
9,482

edits