Loops/Nested: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|F#}}: Corrected header as suggested on the Count examples/Full list/Tier 4 talk page) |
m (→{{header|Wren}}: Minor tidy) |
||
(27 intermediate revisions by 16 users not shown) | |||
Line 27:
=={{header|11l}}==
<
L 10
mat [+]= (1..10).map(x -> random:(1..20))
Line 35:
print(el, end' ‘ ’)
I el == 20
L(row).break</
=={{header|360 Assembly}}==
<
LOOPNEST CSECT
USING LOOPNEST,R12
Line 111:
RANDSEED DC F'16807' running n
YREGS
END LOOPNEST</
{{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!}}==
<
DEFINE PTR="CARD"
BYTE i,j,found
Line 154:
PutE()
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Loops_nested.png Screenshot from Atari 8-bit computer]
Line 166:
=={{header|Ada}}==
<
with Ada.Numerics.Discrete_Random;
Line 186:
New_Line;
end loop Outer;
end Test_Loop_Nested;</
{{out|Sample output}}
<pre>
Line 196:
=={{header|ALGOL 60}}==
{{works with|ALGOL 60|OS/360}}
<
'INTEGER' SEED;
'INTEGER' 'PROCEDURE' RANDOM(N);
Line 217:
'END';
LAB:
'END'</
{{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)}}
<
[10][10]INT a; INT i, j;
Line 248:
xkcd com 292:
print(new line)
)</
{{out|Sample output}}
<pre>
Line 254:
8 9 1 15 3 1 10 19 6 7
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 …
<
set out to {}
repeat with i from 1 to (count array)
Line 273 ⟶ 323:
return out
end loopDemo</
… or of course one or both loops can be specified to terminate at the critical juncture anyway …
<
set out to {}
repeat with i from 1 to (count array)
Line 293 ⟶ 343:
return out
end loopDemo</
… or, with the process in a dedicated handler, it can be returned from directly at any point:
<
set out to {}
repeat with i from 1 to (count array)
Line 309 ⟶ 359:
return out
end loopDemo</
Demo:
<
set array to {}
set stopVal to 20
Line 322 ⟶ 372:
set end of array to row
end repeat
loopDemo(array, stopVal) -- Any of the handlers above.</
{{output}}
<
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program loopnested.s */
Line 558 ⟶ 608:
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}}==
<
{
i := A_Index
Line 584 ⟶ 671:
finish:
MsgBox % "a[" . i . "][" . j . "]" is 20
Return</
=={{header|AWK}}==
To break from two loops, this program uses two <tt>break</tt> statements and one <tt>b</tt> flag.
<
rows = 5
columns = 5
Line 613 ⟶ 700:
print
}
}</
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<
CLS
FOR row = 1 TO 10
Line 630 ⟶ 717:
IF a(row, col) = 20 THEN END
NEXT col
NEXT row</
==={{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.)
Line 637 ⟶ 734:
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
Line 649 ⟶ 746:
100 next c,r
110 print "search complete. no 20 found.":end
</syntaxhighlight>
==={{header|Sinclair ZX81 BASIC}}===
Line 656 ⟶ 753:
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.
<
20 FOR I=1 TO 20
30 FOR J=1 TO 20
Line 667 ⟶ 764:
100 IF CODE A$(I,J)=20 THEN GOTO 130
110 NEXT J
120 NEXT I</
=={{header|BASIC256}}==
<
for i = 0 to 19
Line 686 ⟶ 783:
next i
end</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
FOR row% = 0 TO 10
FOR col% = 0 TO 10
Line 703 ⟶ 800:
NEXT
NEXT row%
</syntaxhighlight>
EXIT FOR can jump out of multiple nested loops by specifying a control variable.
Line 709 ⟶ 806:
Arrays have only one dimension, so we use ''a[i * c + j]'' instead of ''a[i, j]''.
{{trans|AWK}}
<
/* Random number from 1 to 20. */
Line 754 ⟶ 851:
"
}
quit</
=={{header|C}}==
Using goto (note: gotos are [http://en.wikipedia.org/wiki/Considered_harmful considered harmful]):
<
#include <time.h>
#include <stdio.h>
Line 781 ⟶ 878:
printf("\n");
return 0;
}</
Using break, the preferred alternative to goto
<syntaxhighlight lang="c">
#include <stdlib.h>
#include <time.h>
Line 810 ⟶ 907:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
Uses goto as C# has no way to break from multiple loops
<
class Program {
Line 839 ⟶ 936:
Console.WriteLine();
}
}</
Same using Linq :
<
using System.Collections.Generic;
using System.Linq;
Line 867 ⟶ 964:
Console.WriteLine();
}
}</
=={{header|C++}}==
Lambda call:
{{works with|C++11}}
<
#include<ctime>
#include<iostream>
Line 894 ⟶ 991:
})();
return 0;
}</
Goto statement:
{{works with|C++11}}
<
#include<ctime>
#include<iostream>
Line 920 ⟶ 1,017:
return 0;
}</
=={{header|Chapel}}==
<
var nums:[1..10, 1..10] int;
Line 938 ⟶ 1,035:
}
writeln();
}</
=={{header|Clojure}}==
We explicitly return a status flag from the inner loop:
<
(defn create-matrix [width height]
Line 959 ⟶ 1,056:
(when rs (recur rs)))))
(print-matrix (create-matrix 10 10))</
=={{header|COBOL}}==
<
PROGRAM-ID. Nested-Loop.
Line 1,006 ⟶ 1,103:
GOBACK
.</
=={{header|ColdFusion}}==
<
<Cfset RandNum = 0>
<Cfloop condition="randNum neq 20">
Line 1,019 ⟶ 1,116:
<br>
</Cfloop>
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(dotimes (i 10)
(dotimes (j 10)
Line 1,035 ⟶ 1,132:
(return-from outer)))
(terpri))
(terpri)))</
=={{header|D}}==
<
void main() {
Line 1,055 ⟶ 1,152:
writeln();
}</
=={{header|dc}}==
A single ''Q'' command can break multiple nested loops.
{{trans|bc}}
<
[*
Line 1,127 ⟶ 1,224:
]sL
0 d si [i = 0]sz
lb >L [Enter outer loop.]sz</
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}}==
<
matrix: array[1..10,1..10] of Integer;
row, col: Integer;
Line 1,157 ⟶ 1,254:
if Broken then break;
end;
end;</
=={{header|Dyalect}}==
Line 1,163 ⟶ 1,260:
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:
<
for row in array {
for element in row {
print("\(element)")
Line 1,173 ⟶ 1,270:
}
}
}
}
print("*Done")</
{{out}}
Line 1,191 ⟶ 1,286:
=={{header|E}}==
<
escape done {
Line 1,204 ⟶ 1,299:
}
}
println("done.")</
=={{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}}==
<
(lib 'math) ;; for 2D-arrays
(define array (build-array 42 42 (lambda(i j) (1+ (random 20)))))
Line 1,216 ⟶ 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>
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<
def nested do
list = Enum.shuffle(1..20) |> Enum.chunk(5)
Line 1,242 ⟶ 1,350:
end
Loops.nested</
{{out|Sample output}}
Line 1,253 ⟶ 1,361:
'''used Enum.any?'''
<
IO.inspect list, char_lists: :as_lists
Enum.any?(list, fn row ->
Line 1,262 ⟶ 1,370:
end)
end)
IO.puts "done"</
{{out|Sample output}}
Line 1,274 ⟶ 1,382:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( loops_nested ).
Line 1,296 ⟶ 1,404:
random_array( Size ) -> [random:uniform(Size) || _X <- lists:seq(1, Size)].
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
DIM A%[10,10] ! in declaration part
.............
Line 1,318 ⟶ 1,426:
! use a boolean variable or a GOTO label statement
END FOR
</syntaxhighlight>
=={{header|Euphoria}}==
<
a = rand(repeat(repeat(20, 10), 10))
Line 1,338 ⟶ 1,446:
exit
end if
end for</
<code>exit</code> only breaks out of the innermost loop. A better way to do this would be a procedure.
=={{header|F_Sharp|F#}}==
<
//Nigel Galloway: November 10th., 2017
let n = System.Random()
Line 1,348 ⟶ 1,456:
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>
Line 1,357 ⟶ 1,465:
=={{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>.
<
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</
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>).
<
sequences ;
Line 1,369 ⟶ 1,477:
[
[ [ dup pprint bl 20 = [ return ] when ] each nl ] each ! print values until 20 is found
] with-return drop</
{{out}}
<pre>
Line 1,379 ⟶ 1,487:
=={{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.
<
{
public static Void main ()
Line 1,412 ⟶ 1,520:
echo ("No 20")
}
}</
=={{header|Forth}}==
<
10 constant X
Line 1,432 ⟶ 1,540:
20 = if unloop unloop exit then
loop
loop ;</
=={{header|Fortran}}==
{{works with|Fortran|77 and later}}
<
INTEGER A, I, J, RNDINT
Line 1,511 ⟶ 1,619:
ENDIF
RETURN
END</
{{out|Sample output}}
<pre>A[ 1][ 1] is 2
Line 1,530 ⟶ 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.
<
implicit none
Line 1,548 ⟶ 1,656:
end do outer
end program Example</
{{out|Sample output}}
<pre>
Line 1,556 ⟶ 1,664:
=={{header|FreeBASIC}}==
<
Randomize
Line 1,577 ⟶ 1,685:
Print
Print "Press any key to quit"
Sleep</
Sample output :
Line 1,588 ⟶ 1,696:
=={{header|Frink}}==
<
println["array is:\n" + formatTable[array, "right"] + "\n"]
Line 1,601 ⟶ 1,709:
if array@r@c == 20
break ROW
}</
{{out}}
<pre>
Line 1,618 ⟶ 1,726:
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]'''
<
Dim siArray As New Short[5, 5]
Dim siCount0, siCount1 As Short
Line 1,645 ⟶ 1,775:
Print "Row " & Str(siCount0) & " column " & Str(siCount1) & " = 20"
End</
Output:
<pre>
Line 1,652 ⟶ 1,782:
=={{header|GAP}}==
<
n := 40;
a := List([1 .. n], i -> List([1 .. n], j -> Random(1, 20)));;
Line 1,669 ⟶ 1,799:
end;
Find(a, 20);</
=={{header|Go}}==
<
import (
Line 1,703 ⟶ 1,833:
}
fmt.Printf("\n")
}</
=={{header|Groovy}}==
{{Trans|Java}}
Solution:
<
def a = []
(0..<10).each {
Line 1,729 ⟶ 1,859:
}
}
}</
{{out}}
<pre>[1, 19, 14, 16, 3, 12, 14, 18, 12, 6]
Line 1,745 ⟶ 1,875:
=={{header|Haskell}}==
<
breakIncl :: (a -> Bool) -> [a] -> [a]
breakIncl p = uncurry ((. take 1). (++)). break p
taskLLB k = map (breakIncl (==k)). breakIncl (k `elem`)</
{{out|Example}}
<
*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,764 ⟶ 1,894:
10
13
20</
=={{header|HicEst}}==
<
array = NINT( RAN(10,10) )
Line 1,778 ⟶ 1,908:
ENDDO
99 END</
=={{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.
<
every !(!(L := list(10)) := list(10)) := ?20 # setup a 2d array of random numbers up to 20
Line 1,791 ⟶ 1,921:
break break write("L[",i,",",j,"]=20")
end</
<
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</
=={{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.
<
Here's how the problem could be solved, using loops:
<
for_row. i.#y do.
for_col. i.1{$y do.
if. 20=t do.
end.
end.
}}</syntaxhighlight>
{{out|Example use}}
<pre> use ?.20 20 $ 21
Line 1,827 ⟶ 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}}==
<
public class NestedLoopTest {
Line 1,850 ⟶ 1,980:
System.out.println();
}
}</
=={{header|JavaScript}}==
Demonstrates use of <code>break</code> with a label.
Uses <code>print()</code> function from [[Rhino]].
<
var a = [[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1, 20, 16, 5]];
Line 1,867 ⟶ 1,997:
}
}
print("done");</
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,875 ⟶ 2,005:
Using the same data as above, and returning the trail of numbers up to twenty from a nested and composable expression:
<
20, 16, 5]];
Line 1,917 ⟶ 2,047:
return a.concat(x);
}).join('\n')
);</
Output:
<syntaxhighlight lang="javascript">2
12
10
Line 1,940 ⟶ 2,070:
8
13
1</
=={{header|jq}}==
Line 1,947 ⟶ 2,077:
and in this entry, it is used in the following function:
<
# produce a stream of the matrix elements (taken row-wise)
# up to but excluding the first occurrence of $max
Line 1,957 ⟶ 2,087:
| {i: range(0;$m), j: range(0;$n)}
| $matrix[.i][.j] as $m
| if $m == $max then break $ok else $m end ;</
The nesting above could be made more visually explicit, for example, by using
Line 1,971 ⟶ 2,101:
to an array of arrays is useful:
<
# to create successive rows, each row having at most n items.
def reshape(s; n):
Line 1,979 ⟶ 2,109:
else .j += 1
end)
| .matrix;</
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:
<
def randomMatrix(m; n; max):
reshape(limit(m * n; rand(max) + 1); n);
Line 1,993 ⟶ 2,123:
# Main program for the problem at hand.
show(20; 4; 20)</
{{out}}
Line 2,014 ⟶ 2,144:
''' PRNG '''
<
# as rand() from the Microsoft C Runtime.
# Input: [ count, state, random ]
Line 2,030 ⟶ 2,160:
# 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;</
=={{header|Jsish}}==
<
Math.srand(0);
var nrows = Math.floor(Math.random() * 4) + 4;
Line 2,068 ⟶ 2,198:
[ 16, 3, 2, 19, 1, 4, 8, 4, 11, 18 ] ]
=!EXPECTEND!=
*/</
{{out}}
Line 2,075 ⟶ 2,205:
=={{header|Julia}}==
<syntaxhighlight lang="julia">
M = [rand(1:20) for i in 1:5, j in 1:10]
R, C = size(M)
Line 2,093 ⟶ 2,223:
end
end
</syntaxhighlight>
{{out}}
<pre>
Line 2,113 ⟶ 2,243:
=={{header|Kotlin}}==
<
fun main(
val
println("array:")
for (i in a.indices) println("row $i:
println("search:")
print("row $i:
for (j in a[i].indices) {
print(" " + a[i][j])
if (a[i][j] == 20) break@
}
println()
}
println()
}</
{{out}}
<pre>array:
Line 2,145 ⟶ 2,274:
row 9: [20, 16, 5, 13, 15, 9, 3, 2, 2, 16]
search:
row 0:
row 1:
row 2:
=={{header|Lambdatalk}}==
<
1) the A.find function gets a value and a unidimensional array,
then retuns the item matching the value else -1
Line 2,217 ⟶ 2,346:
[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}}==
<
array(2, 12, 10, 4),
array(18, 11, 9, 3),
Line 2,241 ⟶ 2,412:
#1 == 20 ? return
}
}</
=={{header|Liberty BASIC}}==
<
for i = 1 to 10
for j = 1 to 10
Line 2,262 ⟶ 2,433:
if flag then exit for
next
print "Completed row ";x;" and column ";y</
=={{header|Lingo}}==
<
a = []
repeat with i = 1 to 20
Line 2,282 ⟶ 2,453:
end repeat
if v=20 then exit repeat
end repeat</
=={{header|Lisaac}}==
<
+ name := TEST_LOOP_NESTED;
Line 2,319 ⟶ 2,490:
};
'\n'.print;
);</
=={{header|LiveCode}}==
<
repeat with j = 1 to 10
put random(20) into aNums[i,j]
Line 2,342 ⟶ 2,513:
else
put "20 not found"
end if</
=={{header|Logo}}==
<
for [j 1 10] [for [i 1 10] [mdsetitem list :i :j :a (1 + random 20)]]
Line 2,359 ⟶ 2,530:
]
end
until.20</
=={{header|Lua}}==
<
for i = 1, 20 do
t[i] = {}
Line 2,376 ⟶ 2,547:
end
end
print(exitable())</
=={{header|M2000 Interpreter}}==
Line 2,388 ⟶ 2,559:
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Dim A(10,10)<<Random(1, 20)
Line 2,403 ⟶ 2,574:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
<
for i from 1 to m do
for j from 1 to n do
Line 2,414 ⟶ 2,585:
end if;
end do;
end do:</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
If[m[[i, j]] === 20, Return[]],
{i, 1, Dimensions[m][[1]]},
{j, 1, Dimensions[m][[2]]}]</
=={{header|MATLAB}} / {{header|Octave}}==
Loops are considered slow in Matlab and Octave, it is preferable to vectorize the code.
<
[ix,iy]=find(a==20,1)</
A non-vectorized version of the code is shown below in Octave
=={{header|Maxima}}==
<
find_value(a, x) := block(
Line 2,443 ⟶ 2,614:
find_value(data, 100);
not found</
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
fn scan_Nested arr =
(
Line 2,458 ⟶ 2,629:
)
)
</syntaxhighlight>
Example:
<syntaxhighlight lang="maxscript">
testArray = #(#(1,5,2,19),#(11,20,7,2))
scan_nested testArray
Line 2,474 ⟶ 2,645:
OK
</syntaxhighlight>
=={{header|Microsoft Small Basic}}==
<
For col = 0 To 10
array[row][col] = Math.GetRandomNumber(20)
Line 2,490 ⟶ 2,661:
EndFor
EndFor
exit_for_row:</
{{out}}
<pre>row 0 col 0 value 11
Line 2,499 ⟶ 2,670:
=={{header|MOO}}==
<
for i in [1..10]
for j in [1..10]
Line 2,516 ⟶ 2,687:
s = "";
endfor
player:tell(s);</
=={{header|MUMPS}}==
<
;.../loops/nested
;set up the 2D array with random values
Line 2,531 ⟶ 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</
{{out}}
<pre>USER>D NESTLOOP^ROSETTA
Line 2,542 ⟶ 2,713:
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
Loops/Nested in Neko
Tectonics:
Line 2,584 ⟶ 2,755:
if $istrue(inner) break;
row += 1;
}</
{{out}}
Line 2,609 ⟶ 2,780:
{{trans|C#}}
Nemerle can jump out of a named block by invoking the blocks name with an optional return value.
<
using System.Console;
using Nemerle.Imperative;
Line 2,632 ⟶ 2,803:
}
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,662 ⟶ 2,833:
finally
say
end x1</
I was somewhat disappointed by the performance of the above program
and started a little performance analysis on solutions of this task
Line 2,685 ⟶ 2,856:
=={{header|NewLISP}}==
<
(dotimes (i 10)
(dotimes (j 10)
Line 2,695 ⟶ 2,866:
(print " ")
(if (= 20 (a i j))
(throw))))))</
=={{header|Nim}}==
<
const ArrSize = 10
Line 2,722 ⟶ 2,893:
s.add('\n')
echo s</
{{out}}
Line 2,730 ⟶ 2,901:
=={{header|NS-HUBASIC}}==
<
20 FOR I=1 TO 20
30 A(I)=RND(20)+1
Line 2,743 ⟶ 2,914:
120 PRINT A(I);
130 IF A(I)=20 THEN END
140 NEXT</
=={{header|OCaml}}==
Line 2,749 ⟶ 2,920:
In the interactive interpreter:
<
# Random.self_init();;
Line 2,784 ⟶ 2,955:
15 3 5 19 17 3 1 11 5 2
1 1 6 19 20
- : unit = ()</
=={{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")
<
% create a 100x100 matrix...
m = unifrnd(0,20, 100,100);
Line 2,817 ⟶ 2,988:
break;
endif
endfor</
=={{header|OoRexx}}==
<
do i = 1 to 10
do j = 1 to 10
Line 2,833 ⟶ 3,004:
leave i
end
end</
=={{header|Oz}}==
We can directly access and use the outer loop's break procedure:
<
fun {CreateMatrix Width Height}
Matrix = {List.make Height}
Line 2,860 ⟶ 3,031:
end
in
{PrintMatrix {CreateMatrix 10 10}}</
=={{header|PARI/GP}}==
<
for(i=1,10,for(j=1,10,if(M[i,j]==20,break(2))))</
=={{header|Pascal}}==
{{works with|FreePascal|1.0}}
<
uses SysUtils;
const Ni=10; Nj=20;
Line 2,888 ⟶ 3,059:
end;
loopend:
end.</
=={{header|Perl}}==
<
Outer:
Line 2,903 ⟶ 3,074:
print "\n";
}
print "\n";</
=={{header|Phix}}==
use an explicit flag
<!--<
<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,922 ⟶ 3,093:
<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>
<!--</
alternatively you can use a procedure
<!--<
<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,937 ⟶ 3,108:
<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>
<!--</
or a goto
<!--<
<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,953 ⟶ 3,124:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">till20</span><span style="color: #0000FF;">()</span>
<!--</
=={{header|PHP}}==
<
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
Line 2,970 ⟶ 3,141:
}
echo "\n";
?></
=={{header|PicoLisp}}==
<
(T
(for N Lst
(printsp N)
(T (= N 20) T) ) ) )</
or:
<
(for Lst (make (do 10 (link (make (do 10 (link (rand 1 20)))))))
(for N Lst
(printsp N)
(and (= N 20) (throw)) ) ) )</
=={{header|Pike}}==
Line 2,993 ⟶ 3,164:
inner loop. However it's there if you want it:
<syntaxhighlight lang="text">
int main()
{
Line 3,018 ⟶ 3,189:
write("\n");
}
</syntaxhighlight>
=={{header|PL/I}}==
<
x = random()*20 + 1;
loops:
Line 3,030 ⟶ 3,201:
end;
if x(i,j) = 20 then leave;
end;</
=={{header|PureBasic}}==
<
Dim Value(10, 5)
For a = 0 To 10
Line 3,049 ⟶ 3,220:
EndIf
Next
Next</
=={{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:
<
def do_scan(mat):
Line 3,066 ⟶ 3,237:
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)</
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:
<
class Found20(Exception):
Line 3,085 ⟶ 3,256:
print
except Found20:
print</
The second uses a flag variable:
<
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
Line 3,100 ⟶ 3,271:
print
if found20:
break</
=={{header|Qi}}==
<syntaxhighlight lang="qi">
(define random-list
0 -> []
Line 3,119 ⟶ 3,290:
(array->list 20 (random-array 10 10))
</syntaxhighlight>
=={{header|Quackery}}==
<
5 times
[ []
Line 3,144 ⟶ 3,315:
[ echo sp ] ]
iff conclude
else cr ]</
{{out}}
Line 3,161 ⟶ 3,332:
=={{header|R}}==
<
n <- 10
mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m); mat
Line 3,182 ⟶ 3,353:
break
}
}</
or
<syntaxhighlight 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,192 ⟶ 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>
=={{header|Racket}}==
<
#lang racket
(define (scan xss)
Line 3,208 ⟶ 3,379:
(+ (random 20) 1))))
(scan matrix)</
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-18}}
<syntaxhighlight lang="raku"
LINE: for @a -> @line {
Line 3,222 ⟶ 3,393:
print "\n";
}
print "\n";</
{{out}}
<pre> 15 6 14 13 14 7 9 16 8 18
Line 3,230 ⟶ 3,401:
=={{header|REBOL}}==
<
Title: "Loop/Nested"
URL: http://rosettacode.org/wiki/Loop/Nested
Line 3,267 ⟶ 3,438:
]
]
prin crlf</
{{out}}
<pre>Loop break using state variable:
Line 3,288 ⟶ 3,459:
=={{header|ReScript}}==
<
for _ in 0 to 9 {
Line 3,307 ⟶ 3,478:
} catch {
| Exit => Js.log("stop")
}</
=={{header|REXX}}==
Line 3,313 ⟶ 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).
<
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,334 ⟶ 3,505:
say right( space( 'Target' not "found:" ) targ, 33, '─')
/*stick a fork in it, we're all done. */</
'''output''' when using the default inputs:
<pre>
Line 3,370 ⟶ 3,541:
=={{header|Ring}}==
<
size = 5
array = newlist(size,size)
Line 3,394 ⟶ 3,565:
next
return aList
</syntaxhighlight>
Output:
<pre>
Line 3,423 ⟶ 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.
<
p ary
Line 3,440 ⟶ 3,642:
end
puts "done"</
{{out}}
<pre>[[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1, 20, 16, 5]]
Line 3,450 ⟶ 3,652:
However, for-loops are not very popular. This is more idiomatic ruby, which avoids loops and breaking out of them:
<
slices.any? do |slice|
Line 3,459 ⟶ 3,661:
end
end
puts "done"</
{{out}}
<pre>
Line 3,472 ⟶ 3,674:
=={{header|Run BASIC}}==
<
cls
for row = 1 TO 10
Line 3,487 ⟶ 3,689:
next row
[end]
print "At row:";row;" col:";col</
=={{header|Rust}}==
{{libheader|rand}}
<
extern crate rand;
Line 3,512 ⟶ 3,714:
println!();
}
}</
{{out}}
<pre> 5 3 8 18 13 2 5 13 6 17
Line 3,518 ⟶ 3,720:
=={{header|Sather}}==
<
main is
a:ARRAY2{INT} := #(10,10);
Line 3,541 ⟶ 3,743:
end;
end;
end;</
=={{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.
<
val a=Array.fill(5,4)(scala.util.Random.nextInt(21))
println(a map (_.mkString("[", ", ", "]")) mkString "\n")
Line 3,553 ⟶ 3,845:
if (x==20) break
}
}</
{{out}}
<pre>[14, 16, 5, 7]
Line 3,571 ⟶ 3,863:
=={{header|Scheme}}==
Using call/cc:
<
(lambda (return)
(for-each (lambda (a)
Line 3,582 ⟶ 3,874:
a)
(newline))
array)))</
Using tail-call:
<
(if (pair? a)
(let loop2 ((b (car a)))
Line 3,594 ⟶ 3,886:
(else
(display " ")(display (car b))
(loop2 (cdr b)))))))</
=={{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,607 ⟶ 3,899:
printf("\n")
if t(i,j)==11 then break; end
end</
{{out}}
<pre> 5 18 19 8
Line 3,614 ⟶ 3,906:
=={{header|Seed7}}==
<
const proc: main is func
Line 3,641 ⟶ 3,933:
catch FOUND20: writeln;
end block;
end func;</
{{out}}
Line 3,651 ⟶ 3,943:
=={{header|Sidef}}==
<
for row in arr {
Line 3,661 ⟶ 3,953:
} @:OUT
print "\n"</
{{out}}
<pre> 9 17 14 17 17 7 1 3 9 18
Line 3,678 ⟶ 3,970:
it looks a bit wierd, but here is: loopWithExit
<
i := 1.
Line 3,685 ⟶ 3,977:
i == 5 ifTrue:[ exit value:'stopped' ].
i := i + 1.
] loopWithExit</
these can also be nested, and exited from the inner loop:
<
i := 1.
Line 3,701 ⟶ 3,993:
] loopWithExit.
i := i + 1
] loopWithExit</
in case your smalltalk does not have it, here's the definition:
<
loopWithExit
"the receiver must be a block of one argument. It is evaluated in a loop forever,
Line 3,712 ⟶ 4,004:
exitBlock := [:exitValue | ^ exitValue].
[true] whileTrue:[ self value:exitBlock ]</
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:
<
v := 1 to:20 collect:[:i |
Line 3,739 ⟶ 4,031:
] ifFalse:[
'20 found at ' print. result printCR
]</
{{out}}
<pre>19
Line 3,754 ⟶ 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.
<
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,802 ⟶ 4,094:
"loop searching for 20; each block gets the element passed as argument"
biarr whileTrue: [ :v | v ~= 20 ]
do: [ :v | v displayNl ]</
=={{header|SPL}}==
<
mx,my = 30
> y, 1..my
Line 3,819 ⟶ 4,111:
<
<< x!>mx
<</
{{out}}
<pre>
Line 3,834 ⟶ 4,126:
First, build the matrix:
<
forv i=1/20 {
forv j=1/20 {
matrix a[`i',`j']=runiformint(1,20)
}
}</
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.
<
forv i=1/20 {
forv j=1/20 {
Line 3,858 ⟶ 4,150:
if !`q' {
display "not found"
}</
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.
<
local i=1
while !`q' & `i'<=20 {
Line 3,878 ⟶ 4,170:
if !`q' {
display "not found"
}</
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]'''.
<
forv i=1/20 {
forv j=1/20 {
Line 3,899 ⟶ 4,191:
display "not found"
}
else exit _rc</
=== 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.
<
n=rows(a)
p=cols(a)
Line 3,955 ⟶ 4,247:
}
return(q)
}</
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.
<
findval1(a,20,i=.,j=.)
findval2(a,20,i=.,j=.)
findval3(a,20,i=.,j=.)</
=={{header|Swift}}==
<
loop: for row in array {
Line 3,973 ⟶ 4,265:
}
}
print("done")</
{{out}}
<pre> 2
Line 3,987 ⟶ 4,279:
=={{header|Tailspin}}==
In Tailspin you break processing by simply not sending a value on in the chain.
<
sink find20
def a: $;
Line 4,003 ⟶ 4,295:
[1..10 -> [1..10 -> 20 -> SYS::randomInt -> $ + 1]] -> !find20
</syntaxhighlight>
{{out}}
<pre>
Line 4,017 ⟶ 4,309:
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}}
<
try {
Line 4,030 ⟶ 4,322:
}
} trap MULTIBREAK {} {}
puts " done"</
{{out}}
<pre> 12 13 14 13 15,
Line 4,040 ⟶ 4,332:
=={{header|TI-83 BASIC}}==
<
(A,B)→dim([C])
For(I,1,A)
Line 4,057 ⟶ 4,349:
End
3→A:4→B:prgmLOOP</
=={{header|TI-89 BASIC}}==
The <code>Stop</code> statement exits the containing ''program''.
<
Local mat,i,j
© randMat(5, 5) exists but returns -9 to 9 rather than 1 to 20
Line 4,082 ⟶ 4,374:
EndFor
EndFor
EndPrgm</
=={{header|TUSCRIPT}}==
<
LOOP
row=""
Line 4,097 ⟶ 4,389:
ENDLOOP
PRINT row
ENDLOOP</
{{out}}
<pre>
Line 4,109 ⟶ 4,401:
{{works with|Bash}}
Bash doesn't have two-dimentional arrays, so we fake it for this example
<
for ((i=0;i<size;i++)); do
Line 4,127 ⟶ 4,419:
echo
done
echo</
{{out|Example output}}
<pre> 7 5 4 6 4 5 2 15 10 7
Line 4,134 ⟶ 4,426:
=={{header|Vala}}==
<
int[,] a = new int[10, 10];
Line 4,153 ⟶ 4,445:
if (broken) break;
}
}</
=={{header|VBA}}==
<
Dim a(1 To 10, 1 To 10) As Integer
Randomize
Line 4,175 ⟶ 4,467:
Debug.Print
Next i
End Sub</
=={{header|Visual Basic .NET}}==
Line 4,181 ⟶ 4,473:
The set-up code:
<
Sub Main()
Const ROWS = 10
Line 4,200 ⟶ 4,492:
' MISSING IMPLEMENTATION
End Sub
End Module</
'''Implementations:'''
Perhaps the simplest solution is to use a goto.
<
For c = 0 To COLS - 1
Dim val = nums(r, c)
Line 4,212 ⟶ 4,504:
Next
Next
BREAK:</
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).
<
For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Line 4,223 ⟶ 4,515:
Next
Next
Loop While False</
Either For loop can also be converted to a different type of loop.
<
Dim c = 0
Do While c <= COLS - 1
Line 4,234 ⟶ 4,526:
c += 1
Loop
Next</
The search can also be factored out to a separate method
<
For r = 0 To arr.GetLength(0) - 1
For c = 0 To arr.GetLength(1) - 1
Line 4,246 ⟶ 4,538:
Next
Next
End Sub</
and called from Main():
<
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.
<
For c = 0 To COLS - 1
Dim val = nums(r, c)
Line 4,261 ⟶ 4,553:
End If
Next
Next</
Similarly, a flag variable can be checked by the outer loop.
<
For r = 0 To ROWS - 1
For c = 0 To COLS - 1
Line 4,275 ⟶ 4,567:
Next
If done Then Exit For
Next</
{{out}}
Line 4,287 ⟶ 4,579:
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).
<
import "./fmt" for Fmt
var rand = Random.new()
Line 4,305 ⟶ 4,623:
for (i in 0..19) {
for (j in 0..19) {
if (a[i][j] == 20) {
found = true
Line 4,313 ⟶ 4,631:
System.print()
if (found) break
}</
{{out}}
Line 4,325 ⟶ 4,643:
{{works with|Windows XBasic}}
Break out of nested loops by means of an additional variable.
<
PROGRAM "loopsnested"
Line 4,375 ⟶ 4,693:
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 4,404 ⟶ 4,722:
=={{header|XPL0}}==
<
def Size=10;
Line 4,429 ⟶ 4,747:
[Fill(Array);
Nest(Array);
]</
=={{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).
<
var rows=(0).pump(N,List, (0).pump.fp(N,List,(1).random.fpM("1-",21)) );
try{
Line 4,443 ⟶ 4,761:
}
println("Not found");
}catch(Generic){}</
{{out}}
<pre>
Line 4,451 ⟶ 4,769:
=={{header|ZX Spectrum Basic}}==
<
20 FOR i=1 TO 10: FOR j=1 TO 10
30 LET a(i,j)=INT (RND*20)+1
Line 4,462 ⟶ 4,780:
100 IF b=0 THEN PRINT
110 NEXT i
120 STOP </
{{out|Example output}}
<pre>
Line 4,472 ⟶ 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}}
|