Loops/Nested: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|S-BASIC}}: Added alternate approach avoiding GOTO) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
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 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 …
<
set out to {}
repeat with i from 1 to (count array)
Line 273:
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:
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:
return out
end loopDemo</
Demo:
<
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.</
{{output}}
<
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program loopnested.s */
Line 558:
pop {r4, lr}
bx lr
</syntaxhighlight>
=={{header|AutoHotkey}}==
<
{
i := A_Index
Line 584:
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:
print
}
}</
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<
CLS
FOR row = 1 TO 10
Line 630:
IF a(row, col) = 20 THEN END
NEXT col
NEXT row</
==={{header|Applesoft BASIC}}===
<
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</
==={{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">
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>
==={{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.
<
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</
=={{header|BASIC256}}==
<
for i = 0 to 19
Line 696:
next i
end</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
FOR row% = 0 TO 10
FOR col% = 0 TO 10
Line 713:
NEXT
NEXT row%
</syntaxhighlight>
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}}
<
/* Random number from 1 to 20. */
Line 764:
"
}
quit</
=={{header|C}}==
Using goto (note: gotos are [http://en.wikipedia.org/wiki/Considered_harmful considered harmful]):
<
#include <time.h>
#include <stdio.h>
Line 791:
printf("\n");
return 0;
}</
Using break, the preferred alternative to goto
<syntaxhighlight lang="c">
#include <stdlib.h>
#include <time.h>
Line 820:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
Uses goto as C# has no way to break from multiple loops
<
class Program {
Line 849:
Console.WriteLine();
}
}</
Same using Linq :
<
using System.Collections.Generic;
using System.Linq;
Line 877:
Console.WriteLine();
}
}</
=={{header|C++}}==
Lambda call:
{{works with|C++11}}
<
#include<ctime>
#include<iostream>
Line 904:
})();
return 0;
}</
Goto statement:
{{works with|C++11}}
<
#include<ctime>
#include<iostream>
Line 930:
return 0;
}</
=={{header|Chapel}}==
<
var nums:[1..10, 1..10] int;
Line 948:
}
writeln();
}</
=={{header|Clojure}}==
We explicitly return a status flag from the inner loop:
<
(defn create-matrix [width height]
Line 969:
(when rs (recur rs)))))
(print-matrix (create-matrix 10 10))</
=={{header|COBOL}}==
<
PROGRAM-ID. Nested-Loop.
Line 1,016:
GOBACK
.</
=={{header|ColdFusion}}==
<
<Cfset RandNum = 0>
<Cfloop condition="randNum neq 20">
Line 1,029:
<br>
</Cfloop>
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(dotimes (i 10)
(dotimes (j 10)
Line 1,045:
(return-from outer)))
(terpri))
(terpri)))</
=={{header|D}}==
<
void main() {
Line 1,065:
writeln();
}</
=={{header|dc}}==
A single ''Q'' command can break multiple nested loops.
{{trans|bc}}
<
[*
Line 1,137:
]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,167:
if Broken then break;
end;
end;</
=={{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:
<
for row in array {
Line 1,185:
}
}
print("*Done")</
{{out}}
Line 1,199:
=={{header|E}}==
<
escape done {
Line 1,212:
}
}
println("done.")</
=={{header|EchoLisp}}==
<
(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>
=={{header|Elixir}}==
{{works with|Elixir|1.2}}
<
def nested do
list = Enum.shuffle(1..20) |> Enum.chunk(5)
Line 1,250:
end
Loops.nested</
{{out|Sample output}}
Line 1,261:
'''used Enum.any?'''
<
IO.inspect list, char_lists: :as_lists
Enum.any?(list, fn row ->
Line 1,270:
end)
end)
IO.puts "done"</
{{out|Sample output}}
Line 1,282:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( loops_nested ).
Line 1,304:
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,326:
! use a boolean variable or a GOTO label statement
END FOR
</syntaxhighlight>
=={{header|Euphoria}}==
<
a = rand(repeat(repeat(20, 10), 10))
Line 1,346:
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,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>
{{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>.
<
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,377:
[
[ [ dup pprint bl 20 = [ return ] when ] each nl ] each ! print values until 20 is found
] with-return drop</
{{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.
<
{
public static Void main ()
Line 1,420:
echo ("No 20")
}
}</
=={{header|Forth}}==
<
10 constant X
Line 1,440:
20 = if unloop unloop exit then
loop
loop ;</
=={{header|Fortran}}==
{{works with|Fortran|77 and later}}
<
INTEGER A, I, J, RNDINT
Line 1,519:
ENDIF
RETURN
END</
{{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.
<
implicit none
Line 1,556:
end do outer
end program Example</
{{out|Sample output}}
<pre>
Line 1,564:
=={{header|FreeBASIC}}==
<
Randomize
Line 1,585:
Print
Print "Press any key to quit"
Sleep</
Sample output :
Line 1,596:
=={{header|Frink}}==
<
println["array is:\n" + formatTable[array, "right"] + "\n"]
Line 1,609:
if array@r@c == 20
break ROW
}</
{{out}}
<pre>
Line 1,629:
=={{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,653:
Print "Row " & Str(siCount0) & " column " & Str(siCount1) & " = 20"
End</
Output:
<pre>
Line 1,660:
=={{header|GAP}}==
<
n := 40;
a := List([1 .. n], i -> List([1 .. n], j -> Random(1, 20)));;
Line 1,677:
end;
Find(a, 20);</
=={{header|Go}}==
<
import (
Line 1,711:
}
fmt.Printf("\n")
}</
=={{header|Groovy}}==
{{Trans|Java}}
Solution:
<
def a = []
(0..<10).each {
Line 1,737:
}
}
}</
{{out}}
<pre>[1, 19, 14, 16, 3, 12, 14, 18, 12, 6]
Line 1,753:
=={{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,772:
10
13
20</
=={{header|HicEst}}==
<
array = NINT( RAN(10,10) )
Line 1,786:
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,799:
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}}==
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):
<
Here's how the problem could be solved, using loops:
<
for_row. i.#y do.
for_col. i.1{$y do.
Line 1,818:
end.
end.
}}</
{{out|Example use}}
<pre> use ?.20 20 $ 21
Line 1,838:
=={{header|Java}}==
<
public class NestedLoopTest {
Line 1,858:
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,875:
}
}
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,883:
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,925:
return a.concat(x);
}).join('\n')
);</
Output:
<syntaxhighlight lang="javascript">2
12
10
Line 1,948:
8
13
1</
=={{header|jq}}==
Line 1,955:
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,965:
| {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,979:
to an array of arrays is useful:
<
# to create successive rows, each row having at most n items.
def reshape(s; n):
Line 1,987:
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 2,001:
# Main program for the problem at hand.
show(20; 4; 20)</
{{out}}
Line 2,022:
''' PRNG '''
<
# 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;</
=={{header|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!=
*/</
{{out}}
Line 2,083:
=={{header|Julia}}==
<syntaxhighlight 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>
{{out}}
<pre>
Line 2,121:
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 2,139:
}
println()
}</
{{out}}
<pre>array:
Line 2,158:
=={{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,225:
[18,4,2,14,15]
21 was not found
</syntaxhighlight>
=={{header|Lasso}}==
<
array(2, 12, 10, 4),
array(18, 11, 9, 3),
Line 2,249:
#1 == 20 ? return
}
}</
=={{header|Liberty BASIC}}==
<
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</
=={{header|Lingo}}==
<
a = []
repeat with i = 1 to 20
Line 2,290:
end repeat
if v=20 then exit repeat
end repeat</
=={{header|Lisaac}}==
<
+ name := TEST_LOOP_NESTED;
Line 2,327:
};
'\n'.print;
);</
=={{header|LiveCode}}==
<
repeat with j = 1 to 10
put random(20) into aNums[i,j]
Line 2,350:
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,367:
]
end
until.20</
=={{header|Lua}}==
<
for i = 1, 20 do
t[i] = {}
Line 2,384:
end
end
print(exitable())</
=={{header|M2000 Interpreter}}==
Line 2,396:
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Dim A(10,10)<<Random(1, 20)
Line 2,411:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
<
for i from 1 to m do
for j from 1 to n do
Line 2,422:
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,451:
find_value(data, 100);
not found</
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
fn scan_Nested arr =
(
Line 2,466:
)
)
</syntaxhighlight>
Example:
<syntaxhighlight lang="maxscript">
testArray = #(#(1,5,2,19),#(11,20,7,2))
scan_nested testArray
Line 2,482:
OK
</syntaxhighlight>
=={{header|Microsoft Small Basic}}==
<
For col = 0 To 10
array[row][col] = Math.GetRandomNumber(20)
Line 2,498:
EndFor
EndFor
exit_for_row:</
{{out}}
<pre>row 0 col 0 value 11
Line 2,507:
=={{header|MOO}}==
<
for i in [1..10]
for j in [1..10]
Line 2,524:
s = "";
endfor
player:tell(s);</
=={{header|MUMPS}}==
<
;.../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</
{{out}}
<pre>USER>D NESTLOOP^ROSETTA
Line 2,550:
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
Loops/Nested in Neko
Tectonics:
Line 2,592:
if $istrue(inner) break;
row += 1;
}</
{{out}}
Line 2,617:
{{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,640:
}
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,670:
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,693:
=={{header|NewLISP}}==
<
(dotimes (i 10)
(dotimes (j 10)
Line 2,703:
(print " ")
(if (= 20 (a i j))
(throw))))))</
=={{header|Nim}}==
<
const ArrSize = 10
Line 2,730:
s.add('\n')
echo s</
{{out}}
Line 2,738:
=={{header|NS-HUBASIC}}==
<
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</
=={{header|OCaml}}==
Line 2,757:
In the interactive interpreter:
<
# Random.self_init();;
Line 2,792:
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,825:
break;
endif
endfor</
=={{header|OoRexx}}==
<
do i = 1 to 10
do j = 1 to 10
Line 2,841:
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,868:
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,896:
end;
loopend:
end.</
=={{header|Perl}}==
<
Outer:
Line 2,911:
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,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>
<!--</
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,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>
<!--</
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,961:
<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,978:
}
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 3,001:
inner loop. However it's there if you want it:
<syntaxhighlight lang="text">
int main()
{
Line 3,026:
write("\n");
}
</syntaxhighlight>
=={{header|PL/I}}==
<
x = random()*20 + 1;
loops:
Line 3,038:
end;
if x(i,j) = 20 then leave;
end;</
=={{header|PureBasic}}==
<
Dim Value(10, 5)
For a = 0 To 10
Line 3,057:
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,074:
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,093:
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,108:
print
if found20:
break</
=={{header|Qi}}==
<syntaxhighlight lang="qi">
(define random-list
0 -> []
Line 3,127:
(array->list 20 (random-array 10 10))
</syntaxhighlight>
=={{header|Quackery}}==
<
5 times
[ []
Line 3,152:
[ echo sp ] ]
iff conclude
else cr ]</
{{out}}
Line 3,169:
=={{header|R}}==
<
n <- 10
mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m); mat
Line 3,190:
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,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>
=={{header|Racket}}==
<
#lang racket
(define (scan xss)
Line 3,216:
(+ (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,230:
print "\n";
}
print "\n";</
{{out}}
<pre> 15 6 14 13 14 7 9 16 8 18
Line 3,238:
=={{header|REBOL}}==
<
Title: "Loop/Nested"
URL: http://rosettacode.org/wiki/Loop/Nested
Line 3,275:
]
]
prin crlf</
{{out}}
<pre>Loop break using state variable:
Line 3,296:
=={{header|ReScript}}==
<
for _ in 0 to 9 {
Line 3,315:
} catch {
| Exit => Js.log("stop")
}</
=={{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).
<
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. */</
'''output''' when using the default inputs:
<pre>
Line 3,378:
=={{header|Ring}}==
<
size = 5
array = newlist(size,size)
Line 3,402:
next
return aList
</syntaxhighlight>
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.
<
p ary
Line 3,448:
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,458:
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,467:
end
end
puts "done"</
{{out}}
<pre>
Line 3,480:
=={{header|Run BASIC}}==
<
cls
for row = 1 TO 10
Line 3,495:
next row
[end]
print "At row:";row;" col:";col</
=={{header|Rust}}==
{{libheader|rand}}
<
extern crate rand;
Line 3,520:
println!();
}
}</
{{out}}
<pre> 5 3 8 18 13 2 5 13 6 17
Line 3,526:
=={{header|Sather}}==
<
main is
a:ARRAY2{INT} := #(10,10);
Line 3,549:
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
Line 3,594:
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
Line 3,634:
end
</syntaxhighlight>
{{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.
<
val a=Array.fill(5,4)(scala.util.Random.nextInt(21))
println(a map (_.mkString("[", ", ", "]")) mkString "\n")
Line 3,651:
if (x==20) break
}
}</
{{out}}
<pre>[14, 16, 5, 7]
Line 3,669:
=={{header|Scheme}}==
Using call/cc:
<
(lambda (return)
(for-each (lambda (a)
Line 3,680:
a)
(newline))
array)))</
Using tail-call:
<
(if (pair? a)
(let loop2 ((b (car a)))
Line 3,692:
(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,705:
printf("\n")
if t(i,j)==11 then break; end
end</
{{out}}
<pre> 5 18 19 8
Line 3,712:
=={{header|Seed7}}==
<
const proc: main is func
Line 3,739:
catch FOUND20: writeln;
end block;
end func;</
{{out}}
Line 3,749:
=={{header|Sidef}}==
<
for row in arr {
Line 3,759:
} @:OUT
print "\n"</
{{out}}
<pre> 9 17 14 17 17 7 1 3 9 18
Line 3,776:
it looks a bit wierd, but here is: loopWithExit
<
i := 1.
Line 3,783:
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,799:
] 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,810:
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,837:
] ifFalse:[
'20 found at ' print. result printCR
]</
{{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.
<
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 ]</
=={{header|SPL}}==
<
mx,my = 30
> y, 1..my
Line 3,917:
<
<< x!>mx
<</
{{out}}
<pre>
Line 3,932:
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,956:
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,976:
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,997:
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 4,053:
}
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 4,071:
}
}
print("done")</
{{out}}
<pre> 2
Line 4,085:
=={{header|Tailspin}}==
In Tailspin you break processing by simply not sending a value on in the chain.
<
sink find20
def a: $;
Line 4,101:
[1..10 -> [1..10 -> 20 -> SYS::randomInt -> $ + 1]] -> !find20
</syntaxhighlight>
{{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}}
<
try {
Line 4,128:
}
} trap MULTIBREAK {} {}
puts " done"</
{{out}}
<pre> 12 13 14 13 15,
Line 4,138:
=={{header|TI-83 BASIC}}==
<
(A,B)→dim([C])
For(I,1,A)
Line 4,155:
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,180:
EndFor
EndFor
EndPrgm</
=={{header|TUSCRIPT}}==
<
LOOP
row=""
Line 4,195:
ENDLOOP
PRINT row
ENDLOOP</
{{out}}
<pre>
Line 4,207:
{{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,225:
echo
done
echo</
{{out|Example output}}
<pre> 7 5 4 6 4 5 2 15 10 7
Line 4,232:
=={{header|Vala}}==
<
int[,] a = new int[10, 10];
Line 4,251:
if (broken) break;
}
}</
=={{header|VBA}}==
<
Dim a(1 To 10, 1 To 10) As Integer
Randomize
Line 4,273:
Debug.Print
Next i
End Sub</
=={{header|Visual Basic .NET}}==
Line 4,279:
The set-up code:
<
Sub Main()
Const ROWS = 10
Line 4,298:
' 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,310:
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,321:
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,332:
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,344:
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,359:
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,373:
Next
If done Then Exit For
Next</
{{out}}
Line 4,387:
=={{header|Vlang}}==
<
import rand.seed
Line 4,410:
println('')
}
}</
=={{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
Line 4,437:
System.print()
if (found) break
}</
{{out}}
Line 4,449:
{{works with|Windows XBasic}}
Break out of nested loops by means of an additional variable.
<
PROGRAM "loopsnested"
Line 4,499:
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 4,528:
=={{header|XPL0}}==
<
def Size=10;
Line 4,553:
[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,567:
}
println("Not found");
}catch(Generic){}</
{{out}}
<pre>
Line 4,575:
=={{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,586:
100 IF b=0 THEN PRINT
110 NEXT i
120 STOP </
{{out|Example output}}
<pre>
|