Loops/Nested: Difference between revisions

m
syntax highlighting fixup automation
(→‎{{header|S-BASIC}}: Added alternate approach avoiding GOTO)
m (syntax highlighting fixup automation)
Line 27:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">[[Int]] mat
L 10
mat [+]= (1..10).map(x -> random:(1..20))
Line 35:
print(el, end' ‘ ’)
I el == 20
L(row).break</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Loop nested 12/08/2015
LOOPNEST CSECT
USING LOOPNEST,R12
Line 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
Line 118:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
DEFINE PTR="CARD"
BYTE i,j,found
Line 154:
PutE()
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Loops_nested.png Screenshot from Atari 8-bit computer]
Line 166:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
 
Line 186:
New_Line;
end loop Outer;
end Test_Loop_Nested;</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 196:
=={{header|ALGOL 60}}==
{{works with|ALGOL 60|OS/360}}
<langsyntaxhighlight lang="algol60">'BEGIN' 'COMMENT' Loops/Nested - ALGOL60 - 19/06/2018;
'INTEGER' SEED;
'INTEGER' 'PROCEDURE' RANDOM(N);
Line 217:
'END';
LAB:
'END'</langsyntaxhighlight>
{{out}}
<pre>
Line 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 248:
xkcd com 292:
print(new line)
)</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 258:
=={{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 …
<langsyntaxhighlight lang="applescript">on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
Line 273:
return out
end loopDemo</langsyntaxhighlight>
… or of course one or both loops can be specified to terminate at the critical juncture anyway …
<langsyntaxhighlight lang="applescript">on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
Line 293:
return out
end loopDemo</langsyntaxhighlight>
… or, with the process in a dedicated handler, it can be returned from directly at any point:
<langsyntaxhighlight lang="applescript">on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
Line 309:
return out
end loopDemo</langsyntaxhighlight>
 
Demo:
<langsyntaxhighlight lang="applescript">local array, stopVal, row
set array to {}
set stopVal to 20
Line 322:
set end of array to row
end repeat
loopDemo(array, stopVal) -- Any of the handlers above.</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{{15, 8, 9, 8, 9, 9, 10, 16, 3, 6}, {11, 3, 14, 18, 17, 1, 16, 15, 14, 7}, {4, 20}}</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program loopnested.s */
Line 558:
pop {r4, lr}
bx lr
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, 10
{
i := A_Index
Line 584:
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 613:
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 630:
IF a(row, col) = 20 THEN END
NEXT col
NEXT row</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight lang="gwbasic"> 1 C = 5
2 R = 4
3 C = C - 1:R = C - 1: DIM A(C,R)
Line 641:
7 FOR I = 0 TO C
8 PRINT S$A(I,J);:S$ = " "
9 IF A(I,J) < > 20 THEN NEXT I,J</langsyntaxhighlight>
==={{header|Commodore BASIC}}===
We should END gracefully. (The Sinclair example below will produce an error on any Commodore machine.)
Line 647:
Also... What if no 20 is ever found?
 
<syntaxhighlight lang="commodorebasicv2">
<lang CommodoreBASICv2>
10 dim a$(20,20):print "initializing...":print
20 for r=1 to 20:for c=1 to 20
Line 659:
100 next c,r
110 print "search complete. no 20 found.":end
</syntaxhighlight>
</lang>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 666:
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.
 
<langsyntaxhighlight lang="basic"> 10 DIM A$(20,20)
20 FOR I=1 TO 20
30 FOR J=1 TO 20
Line 677:
100 IF CODE A$(I,J)=20 THEN GOTO 130
110 NEXT J
120 NEXT I</langsyntaxhighlight>
 
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256">dim a(20, 20)
 
for i = 0 to 19
Line 696:
next i
 
end</langsyntaxhighlight>
 
 
=={{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 713:
NEXT
NEXT row%
</syntaxhighlight>
</lang>
EXIT FOR can jump out of multiple nested loops by specifying a control variable.
 
Line 719:
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 764:
"
}
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 791:
printf("\n");
return 0;
}</langsyntaxhighlight>
 
Using break, the preferred alternative to goto
<syntaxhighlight lang="c">
<lang C>
#include <stdlib.h>
#include <time.h>
Line 820:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
Uses goto as C# has no way to break from multiple loops
<langsyntaxhighlight lang="csharp">using System;
 
class Program {
Line 849:
Console.WriteLine();
}
}</langsyntaxhighlight>
 
 
Same using Linq :
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 877:
Console.WriteLine();
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Lambda call:
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include<cstdlib>
#include<ctime>
#include<iostream>
Line 904:
})();
return 0;
}</langsyntaxhighlight>
Goto statement:
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include<cstdlib>
#include<ctime>
#include<iostream>
Line 930:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">use Random;
 
var nums:[1..10, 1..10] int;
Line 948:
}
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 969:
(when rs (recur rs)))))
 
(print-matrix (create-matrix 10 10))</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Nested-Loop.
 
Line 1,016:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
<langsyntaxhighlight lang="cfm">
<Cfset RandNum = 0>
<Cfloop condition="randNum neq 20">
Line 1,029:
<br>
</Cfloop>
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(let ((a (make-array '(10 10))))
(dotimes (i 10)
(dotimes (j 10)
Line 1,045:
(return-from outer)))
(terpri))
(terpri)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random;
 
void main() {
Line 1,065:
 
writeln();
}</langsyntaxhighlight>
 
=={{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 1,137:
]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}}==
<langsyntaxhighlight lang="delphi">var
matrix: array[1..10,1..10] of Integer;
row, col: Integer;
Line 1,167:
if Broken then break;
end;
end;</langsyntaxhighlight>
 
=={{header|Dyalect}}==
Line 1,173:
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:
 
<langsyntaxhighlight lang="dyalect">let array = [[2, 12, 10, 4], [18, 11, 20, 2]]
for row in array {
Line 1,185:
}
}
print("*Done")</langsyntaxhighlight>
 
{{out}}
Line 1,199:
 
=={{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 1,212:
}
}
println("done.")</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(lib 'math) ;; for 2D-arrays
(define array (build-array 42 42 (lambda(i j) (1+ (random 20)))))
Line 1,224:
→ 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}}
<langsyntaxhighlight lang="elixir">defmodule Loops do
def nested do
list = Enum.shuffle(1..20) |> Enum.chunk(5)
Line 1,250:
end
 
Loops.nested</langsyntaxhighlight>
 
{{out|Sample output}}
Line 1,261:
 
'''used Enum.any?'''
<langsyntaxhighlight lang="elixir">list = Enum.shuffle(1..20) |> Enum.chunk(5)
IO.inspect list, char_lists: :as_lists
Enum.any?(list, fn row ->
Line 1,270:
end)
end)
IO.puts "done"</langsyntaxhighlight>
 
{{out|Sample output}}
Line 1,282:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( loops_nested ).
 
Line 1,304:
 
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 1,326:
! 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 1,346:
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#}}==
<langsyntaxhighlight lang="fsharp">
//Nigel Galloway: November 10th., 2017
let n = System.Random()
Line 1,356:
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>
</lang>
{{out}}
<pre>
Line 1,365:
=={{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>.
<langsyntaxhighlight 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</langsyntaxhighlight>
 
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>).
<langsyntaxhighlight lang="factor">USING: continuations io kernel math.ranges prettyprint random
sequences ;
 
Line 1,377:
[
[ [ dup pprint bl 20 = [ return ] when ] each nl ] each ! print values until 20 is found
] with-return drop</langsyntaxhighlight>
{{out}}
<pre>
Line 1,387:
=={{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 1,420:
echo ("No 20")
}
}</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">include random.fs
 
10 constant X
Line 1,440:
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 1,519:
ENDIF
RETURN
END</langsyntaxhighlight>
{{out|Sample output}}
<pre>A[ 1][ 1] is 2
Line 1,538:
{{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 1,556:
end do outer
end program Example</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 1,564:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Randomize
Line 1,585:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
Sample output :
Line 1,596:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">array = new array[[10,10], {|x,y| random[1,20]}]
 
println["array is:\n" + formatTable[array, "right"] + "\n"]
Line 1,609:
if array@r@c == 20
break ROW
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,629:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=77521a9ffe6bebdfe2e34df8faab5e78 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siArray As New Short[5, 5]
Dim siCount0, siCount1 As Short
Line 1,653:
Print "Row " & Str(siCount0) & " column " & Str(siCount1) & " = 20"
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,660:
 
=={{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 1,677:
end;
 
Find(a, 20);</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,711:
}
fmt.Printf("\n")
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
{{Trans|Java}}
Solution:
<langsyntaxhighlight lang="groovy">final random = new Random()
def a = []
(0..<10).each {
Line 1,737:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>[1, 19, 14, 16, 3, 12, 14, 18, 12, 6]
Line 1,753:
 
=={{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}}
<langsyntaxhighlight lang="haskell">
*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]]
2
Line 1,772:
10
13
20</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: n=20, array(n,n)
 
array = NINT( RAN(10,10) )
Line 1,786:
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,799:
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}}==
Line 1,809:
 
So, here's how the problem statement 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=: {{
for_row. i.#y do.
for_col. i.1{$y do.
Line 1,818:
end.
end.
}}</langsyntaxhighlight>
{{out|Example use}}
<pre> use ?.20 20 $ 21
Line 1,838:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Random;
 
public class NestedLoopTest {
Line 1,858:
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,875:
}
}
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,883:
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,925:
return a.concat(x);
}).join('\n')
);</langsyntaxhighlight>
 
Output:
<syntaxhighlight lang="javascript">2
<lang JavaScript>2
12
10
Line 1,948:
8
13
1</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,955:
and in this entry, it is used in the following function:
 
<langsyntaxhighlight 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
Line 1,965:
| {i: range(0;$m), j: range(0;$n)}
| $matrix[.i][.j] as $m
| if $m == $max then break $ok else $m end ;</langsyntaxhighlight>
 
The nesting above could be made more visually explicit, for example, by using
Line 1,979:
to an array of arrays is useful:
 
<langsyntaxhighlight 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):
Line 1,987:
else .j += 1
end)
| .matrix;</langsyntaxhighlight>
 
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:
<langsyntaxhighlight 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);
Line 2,001:
 
# Main program for the problem at hand.
show(20; 4; 20)</langsyntaxhighlight>
 
{{out}}
Line 2,022:
 
''' PRNG '''
<langsyntaxhighlight lang="jq"># LCG::Microsoft generates 15-bit integers using the same formula
# as rand() from the Microsoft C Runtime.
# Input: [ count, state, random ]
Line 2,038:
# 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;</langsyntaxhighlight>
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Loops/Nested in Jsish */
Math.srand(0);
var nrows = Math.floor(Math.random() * 4) + 4;
Line 2,076:
[ 16, 3, 2, 19, 1, 4, 8, 4, 11, 18 ] ]
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 2,083:
 
=={{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 2,101:
end
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,121:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">import java.util.Random
 
fun main(args: Array<String>) {
Line 2,139:
}
println()
}</langsyntaxhighlight>
{{out}}
<pre>array:
Line 2,158:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
1) the A.find function gets a value and a unidimensional array,
then retuns the item matching the value else -1
Line 2,225:
[18,4,2,14,15]
21 was not found
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
 
<langsyntaxhighlight Lassolang="lasso">local(a) = array(
array(2, 12, 10, 4),
array(18, 11, 9, 3),
Line 2,249:
#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 2,270:
if flag then exit for
next
print "Completed row ";x;" and column ";y</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- create two-dimensional array with random numbers
a = []
repeat with i = 1 to 20
Line 2,290:
end repeat
if v=20 then exit repeat
end repeat</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">Section Header
 
+ name := TEST_LOOP_NESTED;
Line 2,327:
};
'\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 2,350:
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 2,367:
]
end
until.20</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">t = {}
for i = 1, 20 do
t[i] = {}
Line 2,384:
end
end
print(exitable())</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 2,396:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Dim A(10,10)<<Random(1, 20)
Line 2,411:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{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 2,422:
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 2,451:
 
find_value(data, 100);
not found</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
fn scan_Nested arr =
(
Line 2,466:
)
)
</syntaxhighlight>
</lang>
 
Example:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
testArray = #(#(1,5,2,19),#(11,20,7,2))
scan_nested testArray
Line 2,482:
OK
 
</syntaxhighlight>
</lang>
 
=={{header|Microsoft Small Basic}}==
<langsyntaxhighlight lang="smallbasic">For row = 0 To 10
For col = 0 To 10
array[row][col] = Math.GetRandomNumber(20)
Line 2,498:
EndFor
EndFor
exit_for_row:</langsyntaxhighlight>
{{out}}
<pre>row 0 col 0 value 11
Line 2,507:
 
=={{header|MOO}}==
<langsyntaxhighlight lang="moo">a = make(10, make(10));
for i in [1..10]
for j in [1..10]
Line 2,524:
s = "";
endfor
player:tell(s);</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">NESTLOOP
;.../loops/nested
;set up the 2D array with random values
Line 2,539:
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 2,550:
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
Loops/Nested in Neko
Tectonics:
Line 2,592:
if $istrue(inner) break;
row += 1;
}</langsyntaxhighlight>
 
{{out}}
Line 2,617:
{{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 2,640:
}
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 2,670:
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 2,693:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(let (a (array 10 10))
(dotimes (i 10)
(dotimes (j 10)
Line 2,703:
(print " ")
(if (= 20 (a i j))
(throw))))))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import random, strutils
 
const ArrSize = 10
Line 2,730:
s.add('\n')
 
echo s</langsyntaxhighlight>
 
{{out}}
Line 2,738:
 
=={{header|NS-HUBASIC}}==
<langsyntaxhighlight NSlang="ns-HUBASIChubasic">10 DIM A(20)
20 FOR I=1 TO 20
30 A(I)=RND(20)+1
Line 2,751:
120 PRINT A(I);
130 IF A(I)=20 THEN END
140 NEXT</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 2,757:
In the interactive interpreter:
 
<langsyntaxhighlight lang="ocaml">$ ocaml
 
# Random.self_init();;
Line 2,792:
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 2,825:
break;
endif
endfor</langsyntaxhighlight>
 
=={{header|OoRexx}}==
<langsyntaxhighlight lang="oorexx">numbers = .array~new()
do i = 1 to 10
do j = 1 to 10
Line 2,841:
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 2,868:
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 2,896:
end;
loopend:
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my $a = [ map [ map { int(rand(20)) + 1 } 1 .. 10 ], 1 .. 10];
 
Outer:
Line 2,911:
print "\n";
}
print "\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
use an explicit flag
<!--<langsyntaxhighlight Phixlang="phix">-->
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Line 2,930:
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
alternatively you can use a procedure
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">till20</span><span style="color: #0000FF;">()</span>
<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>
Line 2,945:
<span style="color: #000000;">till20</span><span style="color: #0000FF;">()</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>
<!--</langsyntaxhighlight>-->
or a goto
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">till20</span><span style="color: #0000FF;">()</span>
<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>
Line 2,961:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">till20</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
Line 2,978:
}
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}}==
Line 3,001:
inner loop. However it's there if you want it:
 
<syntaxhighlight lang="text">
int main()
{
Line 3,026:
write("\n");
}
</syntaxhighlight>
</lang>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii"> declare x(20,20) fixed; /* 16 August 2010. */
x = random()*20 + 1;
loops:
Line 3,038:
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 3,057:
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 3,074:
 
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 3,093:
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 3,108:
print
if found20:
break</langsyntaxhighlight>
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
<lang Qi>
(define random-list
0 -> []
Line 3,127:
 
(array->list 20 (random-array 10 10))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> []
5 times
[ []
Line 3,152:
[ echo sp ] ]
iff conclude
else cr ]</langsyntaxhighlight>
 
{{out}}
Line 3,169:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">m <- 10
n <- 10
mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m); mat
Line 3,190:
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 3,200:
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 3,216:
(+ (random 20) 1))))
 
(scan matrix)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-18}}
<syntaxhighlight lang="raku" perl6line>my @a = [ (1..20).roll(10) ] xx *;
 
LINE: for @a -> @line {
Line 3,230:
print "\n";
}
print "\n";</langsyntaxhighlight>
{{out}}
<pre> 15 6 14 13 14 7 9 16 8 18
Line 3,238:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Loop/Nested"
URL: http://rosettacode.org/wiki/Loop/Nested
Line 3,275:
]
]
prin crlf</langsyntaxhighlight>
{{out}}
<pre>Loop break using state variable:
Line 3,296:
 
=={{header|ReScript}}==
<langsyntaxhighlight ReScriptlang="rescript">let m = []
 
for _ in 0 to 9 {
Line 3,315:
} catch {
| Exit => Js.log("stop")
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 3,321:
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 two-dimensional array to search for a '20' (twenty). */
parse arg rows cols targ . /*obtain optional arguments from the CL*/
if rows=='' | rows=="," then rows=60 /*Rows not specified? Then use default*/
Line 3,342:
 
say right( space( 'Target' not "found:" ) targ, 33, '─')
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; when using the default inputs:
<pre>
Line 3,378:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
size = 5
array = newlist(size,size)
Line 3,402:
next
return aList
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,435:
As the break command only jumps out of the innermost loop,
this task requires Ruby's <code>catch/throw</code> functionality.
<langsyntaxhighlight lang="ruby">ary = (1..20).to_a.shuffle.each_slice(4).to_a
p ary
 
Line 3,448:
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 3,458:
 
However, for-loops are not very popular. This is more idiomatic ruby, which avoids loops and breaking out of them:
<langsyntaxhighlight lang="ruby">p slices = [*1..20].shuffle.each_slice(4)
 
slices.any? do |slice|
Line 3,467:
end
end
puts "done"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,480:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim a(10,10)
cls
for row = 1 TO 10
Line 3,495:
next row
[end]
print "At row:";row;" col:";col</langsyntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">use rand::Rng;
 
extern crate rand;
Line 3,520:
println!();
}
}</langsyntaxhighlight>
{{out}}
<pre> 5 3 8 18 13 2 5 13 6 17
Line 3,526:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
a:ARRAY2{INT} := #(10,10);
Line 3,549:
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">
<lang BASIC>
$constant ROWS = 10
$constant COLUMNS = 10
Line 3,594:
 
end
</syntaxhighlight>
</lang>
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">
<lang BASIC>
$constant ROWS = 10
$constant COLUMNS = 10
Line 3,634:
 
end
</syntaxhighlight>
</lang>
{{out}}
The output is the same for both programs.
Line 3,643:
=={{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 3,651:
if (x==20) break
}
}</langsyntaxhighlight>
{{out}}
<pre>[14, 16, 5, 7]
Line 3,669:
=={{header|Scheme}}==
Using call/cc:
<langsyntaxhighlight lang="scheme">(call-with-current-continuation
(lambda (return)
(for-each (lambda (a)
Line 3,680:
a)
(newline))
array)))</langsyntaxhighlight>
Using tail-call:
<langsyntaxhighlight lang="scheme">(let loop ((a array))
(if (pair? a)
(let loop2 ((b (car a)))
Line 3,692:
(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 3,705:
printf("\n")
if t(i,j)==11 then break; end
end</langsyntaxhighlight>
{{out}}
<pre> 5 18 19 8
Line 3,712:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 3,739:
catch FOUND20: writeln;
end block;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,749:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = 10.of{ 10.of{ 20.irand + 1 } }
 
for row in arr {
Line 3,759:
} @:OUT
 
print "\n"</langsyntaxhighlight>
{{out}}
<pre> 9 17 14 17 17 7 1 3 9 18
Line 3,776:
it looks a bit wierd, but here is: loopWithExit
 
<langsyntaxhighlight lang="smalltalk">|i|
 
i := 1.
Line 3,783:
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 3,799:
] 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 3,810:
 
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 3,837:
] ifFalse:[
'20 found at ' print. result printCR
]</langsyntaxhighlight>
{{out}}
<pre>19
Line 3,852:
 
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 3,900:
"loop searching for 20; each block gets the element passed as argument"
biarr whileTrue: [ :v | v ~= 20 ]
do: [ :v | v displayNl ]</langsyntaxhighlight>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">'fill array
mx,my = 30
> y, 1..my
Line 3,917:
<
<< x!>mx
<</langsyntaxhighlight>
{{out}}
<pre>
Line 3,932:
First, build the matrix:
 
<langsyntaxhighlight lang="stata">matrix a=J(20,20,0)
forv i=1/20 {
forv j=1/20 {
matrix a[`i',`j']=runiformint(1,20)
}
}</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="stata">local q 0
forv i=1/20 {
forv j=1/20 {
Line 3,956:
if !`q' {
display "not found"
}</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="stata">local q 0
local i=1
while !`q' & `i'<=20 {
Line 3,976:
if !`q' {
display "not found"
}</langsyntaxhighlight>
 
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]'''.
 
<langsyntaxhighlight lang="stata">capture {
forv i=1/20 {
forv j=1/20 {
Line 3,997:
display "not found"
}
else exit _rc</langsyntaxhighlight>
 
=== 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.
 
<langsyntaxhighlight lang="stata">function findval1(a,x,i0,j0) {
n=rows(a)
p=cols(a)
Line 4,053:
}
return(q)
}</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="stata">a=st_matrix("a")
findval1(a,20,i=.,j=.)
findval2(a,20,i=.,j=.)
findval3(a,20,i=.,j=.)</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">let array = [[2, 12, 10, 4], [18, 11, 20, 2]]
 
loop: for row in array {
Line 4,071:
}
}
print("done")</langsyntaxhighlight>
{{out}}
<pre> 2
Line 4,085:
=={{header|Tailspin}}==
In Tailspin you break processing by simply not sending a value on in the chain.
<langsyntaxhighlight lang="tailspin">
sink find20
def a: $;
Line 4,101:
 
[1..10 -> [1..10 -> 20 -> SYS::randomInt -> $ + 1]] -> !find20
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,115:
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 4,128:
}
} trap MULTIBREAK {} {}
puts " done"</langsyntaxhighlight>
{{out}}
<pre> 12 13 14 13 15,
Line 4,138:
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti83b">PROGRAM:LOOP
(A,B)→dim([C])
For(I,1,A)
Line 4,155:
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 4,180:
EndFor
EndFor
EndPrgm</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
LOOP
row=""
Line 4,195:
ENDLOOP
PRINT row
ENDLOOP</langsyntaxhighlight>
{{out}}
<pre>
Line 4,207:
{{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 4,225:
echo
done
echo</langsyntaxhighlight>
{{out|Example output}}
<pre> 7 5 4 6 4 5 2 15 10 7
Line 4,232:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">void main() {
int[,] a = new int[10, 10];
Line 4,251:
if (broken) break;
}
}</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight VBlang="vb">Public Sub LoopsNested()
Dim a(1 To 10, 1 To 10) As Integer
Randomize
Line 4,273:
Debug.Print
Next i
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
Line 4,279:
 
The set-up code:
<langsyntaxhighlight lang="vbnet">Module Program
Sub Main()
Const ROWS = 10
Line 4,298:
' MISSING IMPLEMENTATION
End Sub
End Module</langsyntaxhighlight>
 
'''Implementations:'''
 
Perhaps the simplest solution is to use a goto.
<langsyntaxhighlight lang="vbnet"> For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Dim val = nums(r, c)
Line 4,310:
Next
Next
BREAK:</langsyntaxhighlight>
 
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).
<langsyntaxhighlight lang="vbnet"> Do
For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Line 4,321:
Next
Next
Loop While False</langsyntaxhighlight>
 
Either For loop can also be converted to a different type of loop.
<langsyntaxhighlight lang="vbnet"> For r = 0 To ROWS - 1
Dim c = 0
Do While c <= COLS - 1
Line 4,332:
c += 1
Loop
Next</langsyntaxhighlight>
 
The search can also be factored out to a separate method
<langsyntaxhighlight lang="vbnet"> Sub Find20Impl(arr As Integer(,))
For r = 0 To arr.GetLength(0) - 1
For c = 0 To arr.GetLength(1) - 1
Line 4,344:
Next
Next
End Sub</langsyntaxhighlight>
 
and called from Main():
<langsyntaxhighlight lang="vbnet"> Find20Impl(nums)</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="vbnet"> For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Dim val = nums(r, c)
Line 4,359:
End If
Next
Next</langsyntaxhighlight>
 
Similarly, a flag variable can be checked by the outer loop.
<langsyntaxhighlight lang="vbnet"> Dim done = False
For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Line 4,373:
Next
If done Then Exit For
Next</langsyntaxhighlight>
 
{{out}}
Line 4,387:
 
=={{header|Vlang}}==
<langsyntaxhighlight lang="vlang">import rand
import rand.seed
 
Line 4,410:
println('')
}
}</langsyntaxhighlight>
 
=={{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).
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
 
Line 4,437:
System.print()
if (found) break
}</langsyntaxhighlight>
 
{{out}}
Line 4,449:
{{works with|Windows XBasic}}
Break out of nested loops by means of an additional variable.
<langsyntaxhighlight lang="xbasic">
PROGRAM "loopsnested"
 
Line 4,499:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,528:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def Size=10;
 
Line 4,553:
[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 4,567:
}
println("Not found");
}catch(Generic){}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,575:
 
=={{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 4,586:
100 IF b=0 THEN PRINT
110 NEXT i
120 STOP </langsyntaxhighlight>
{{out|Example output}}
<pre>
10,327

edits