Anonymous user
Loop structures: Difference between revisions
no edit summary
(→What are loops?: +> repetition) |
imported>Maleza No edit summary |
||
(49 intermediate revisions by 18 users not shown) | |||
Line 2:
[[Category:Maintenance]]In this former task, we document loop structures offered by different languages.
Loops are control structures that allow sections of code to be executed repeatedly according to the controlling conditions of the loop.
Line 8:
There are two types of loops:
;Repetition:
Additionally, there is the overly simple repetitive loop: [[repeat|repetition]]. The simplistic construct executes a block of code, or a procedure, a given number of times, without explicitly exposing any state change to the looped procedure.
An [[:Category:Iteration|iterative loop]] repeatedly executes a set of instructions as the iterator steps through a series of values. Types of iterative loops include [[
;Conditional loops:
A [[conditional loop]] tests for a condition around the loop, and repeatedly executes a block of [[instruction]]s whilst the [[condition]] is true. Types of [[conditional loop]]s include [[while loop]]s and [[do-while loop]]s.
'''Examples here should be migrated to an appropriate [[:Category:Iteration|Iteration]] page and removed from here. If a page does not exist demonstrating a particular loop structure, discuss it [[:Category talk:Iteration|here]].'''
<br><br>
=={{header|68000 Assembly}}==
'''NOT COVERED IN LOOP PAGES'''
The 68000 uses <code>DBxx Dn, label</code> for loop counting. "Dn" refers to a chosen data register. The "xx" is replaced with the condition code of your choice (<code>DBRA</code> stands for Decrement, Branch Always which is most commonly used). Execution will jump to the labeled line of code unless Dn's lower two bytes equal #$FFFF or the specified condition code is true, whichever occurs first. Keep in mind that the condition code has nothing to do with the value stored in Dn; rather, it represents the outcome of the operation just before the branch. This is similar to a "repeat until" construct in some other languages.
The below code snippet represents a loop that continues until a value greater than 3500 is read. However, it will also end after the 2000th iteration automatically, regardless of whether the condition is ever met.
<syntaxhighlight lang="68000devpac">
MOVE.W #1999,D1 ;DBxx loop counters need to be pre-decremented to work properly, since they terminate at $FFFF rather than 0
LOOP:
MOVE.W (A0)+,D0
CMP.W #3501,D0 ;COMPARE TO #3501
DBCC D1,LOOP ;DECREMENT, BRANCH UNTIL CARRY CLEAR OR D1 = #$FFFF
</syntaxhighlight>
=={{header|AmbientTalk}}==
===doTimes===
<
20.doTimes { |i| system.print(" "+i); }
</syntaxhighlight>
===each===
Iterate over a collection:
<syntaxhighlight lang="ambienttalk">
[ "foo", "bar", "baz" ].each: { |e|
system.print(" "+e);
}
// prints: foo bar baz
</syntaxhighlight>
==[[AppleScript]]==
'''NOT COVERED IN LOOP PAGES'''
===repeat-until===
<syntaxhighlight lang="applescript>
set i to 5
repeat
set i to i - 1
end repeat
</syntaxhighlight>
===repeat-with===
<syntaxhighlight lang="applescript>
repeat with i from 1 to 20
end repeat
</syntaxhighlight>
==[[AssemblyScript]]==
'''NOT COVERING ALL POSSIBLE LOOP OPTIONS'''
===while===
<syntaxhighlight lang="javascript">
let done = false
while (!done) {
done = true
}
</syntaxhighlight>
===do while===
<syntaxhighlight lang="javascript">
let done = false
do {
done = true
} while (!done)
</syntaxhighlight>
===for===
<syntaxhighlight lang="javascript">
for (let i = 0; i < 10000; i++) {
i += i
}
</syntaxhighlight>
==[[Brainf***]]==
Line 80 ⟶ 122:
A compile-time for loop can be generated with template metaprogramming. Example:
<syntaxhighlight lang="cpp">
// the loop
template<int start, int finish, template<int n, typename T> class X> struct loop
{
typedef typename X<start, typename loop<start+1, finish, X>::type>::type type;
};
</syntaxhighlight>
==[[Clojure]]==
'''NOT COVERED IN LOOP PAGES'''
===loop===
<
(loop [lst [1 3 5 7]
ret []]
Line 120 ⟶ 164:
ret))
==> [1 9 25 49]
</syntaxhighlight>
=={{header|Crack}}==
===For===
<
for( i=0; i<9; i++)
cout ` $i\n`;
</syntaxhighlight>
=={{header|Curto}}==
===HACER-BUCLE===
<syntaxhighlight lang="curto">
\ limite inicio HACER sentencias iteradas BUCLE
\ limite inicio HACER sentencias iteradas incremento +BUCLE
\ SALIR \ abandona bucle HACER
\ DBUCLE SALIR \ limpia contadores de la pila de retorno antes de abandonar la palabra actual
</syntaxhighlight>
ejemplo: Dos iteraciones típicas
<syntaxhighlight lang="curto">
10 0 hacer i . bucle \ Imprime números de 0 a 9
10 0 hacer i . 2 +bucle \ Imprime números pares de 0 a 8
</syntaxhighlight>
===EMPEZAR-HASTA===
<syntaxhighlight lang="curto">
\ EMPEZAR sentencias iteradas condicional HASTA
</syntaxhighlight>
ejemplo: Cuenta hacia abajo desde un número dado a cero
<syntaxhighlight lang="curto">
: cuenta-abajo ( n -- ) empezar dup rc . 1- dup 0< hasta soltar ;
</syntaxhighlight>
===EMPEZAR-DENUEVO===
<syntaxhighlight lang="curto">
\ EMPEZAR sentencias iteradas DENUEVO
</syntaxhighlight>
ejemplo: repetir entrada de usuario (solo funciona en cli, no en la interface gráfica)
<syntaxhighlight lang="curto">
: porsiempre ( -- ) empezar tecla emitir denuevo ;
</syntaxhighlight>
===EMPEZAR-MIENTRAS-REPETIR===
<syntaxhighlight lang="curto">
\ EMPEZAR sentencias iteradas incondicionales condicional MIENTRAS sentencias iteradas condicionales repetir
</syntaxhighlight>
ejemplo: cuenta hacia abajo desde un número dado a uno
<syntaxhighlight>
: cuenta-abajo ( n -- ) empezar dup mientras rc dup . 1- repetir soltar ;
</syntaxhighlight>
=={{header|Dafny}}==
<syntaxhighlight lang="dafny">
var i: int := 0;
while i < n
invariant 0 <= i <= n
decreases n - i
{
i := i + 1;
}
assert i == n;
</syntaxhighlight>
=={{header|Dao}}==
===For===
<syntaxhighlight lang="java">
for( i
for( i = 0 : 8 ) io.writeln( i );</syntaxhighlight>
===For In===
<syntaxhighlight lang="java">
items = { 1, 2, 3 }
for( item in items ) io.writeln( item )
</syntaxhighlight>
===While===
<syntaxhighlight lang="java">
i = 0
while( i < 5 ) { i += 1 }
</syntaxhighlight>
===Do While===
<syntaxhighlight lang="java">
i = 0
do { i += 1 } while( i < 9 )
</syntaxhighlight>
=={{header|Déjà Vu}}==
===For===
Déjà Vu has a for-loop protocol, so you can write your own iterators. The most commonly used iterators are <code>in</code> and <code>range</code>. The first iterates over a list, the second takes two arguments and goes from the first to the second, like a classic for-loop.
<syntaxhighlight lang
for i range 1 3:
!print i # prints 1, 2 and 3
</syntaxhighlight>
===While===
<syntaxhighlight lang
while true:
!print "This is the song that never ends..."
</syntaxhighlight>
===Repeat===
<syntaxhighlight lang
repeat 3:
!print "This sentence is printed three times."
</syntaxhighlight>
==[[Factor]]==
Line 158 ⟶ 274:
===Looping===
Most looping is done with recursion. Tail recursion is properly optimized.
<syntaxhighlight lang="factor">
: forever ( quot -- ) dup slip forever ; inline
[ "A hungry raptor stalks you..." print flush 2000 random sleep ] forever
</syntaxhighlight>
===Iteration===
<syntaxhighlight lang="factor">
Most indices are implicit or not present at all.
</syntaxhighlight>
Iterating with an index:
<syntaxhighlight lang="factor">
: indexed-alphabet. ( -- )
"abcdefghijklmnopqrstuvwxyz"
[ [ 1string ] [ number>string ] bi* ": " glue print ] each-index ;
</syntaxhighlight>
==[[Forth]]==
===DO-LOOP===
<syntaxhighlight lang="forth">
( limit start ) DO ( iterated statements ) ( increment ) +LOOP
LEAVE \ exits a DO loop
UNLOOP EXIT \ cleans up loop counters from return stack before returning from the current word
</syntaxhighlight>
example: Two standard iterations
<syntaxhighlight lang="forth">
10 0 DO I . 2 +LOOP \ Prints the even numbers from 0 to 8
</syntaxhighlight>
===BEGIN-UNTIL===
<syntaxhighlight lang="forth">
BEGIN ( iterated statements ) ( conditional ) UNTIL
</syntaxhighlight>
example: Counts down from a given number to zero
<syntaxhighlight lang="forth">
: COUNTDOWN ( n -- ) BEGIN DUP CR . 1- DUP 0< UNTIL DROP ;
</syntaxhighlight>
===BEGIN-AGAIN===
<syntaxhighlight lang="forth">
BEGIN ( iterated statements ) AGAIN
</syntaxhighlight>
example: echo user's input
<syntaxhighlight lang="forth">
: FOREVER ( -- ) BEGIN KEY EMIT AGAIN ;
</syntaxhighlight>
===BEGIN-WHILE-REPEAT===
<syntaxhighlight lang="forth">
BEGIN ( unconditional iterated statements ) ( conditional ) WHILE ( conditional iterated statements ) REPEAT
example: counts down from a given number to one
</syntaxhighlight>
Additional WHILE clauses may be added to a loop, but each extra WHILE requires a matching THEN after the REPEAT.
Line 214 ⟶ 355:
A good example of a useful combination is this complex loop:
<syntaxhighlight lang="forth">
BEGIN
( condition 1 )
WHILE
( condition 2 )
UNTIL
( condition 2 succeeded )
ELSE
( condition 1 failed )
THEN
</syntaxhighlight>
An example of using this idiom in practice might be this pseudo-Forth
<syntaxhighlight lang="forth">
BEGIN
read-next-record
WHILE
found-record
UNTIL
process-record
ELSE
error" Ran out of records looking for the right one!"
THEN
</syntaxhighlight>
=={{header|FreeBASIC}}==
<h3>[[While_loop|While..Wend]]</h3>
Executes a block of statements while a condition is met.<br>
<syntaxhighlight lang="vbnet">While [ condition ]
[ statement block ]
Wend</syntaxhighlight>
<h3>[[For_loop|For..Next]]</h3>
Executes a block of statements while an iterator is less than or greater than an expression.<br>
<syntaxhighlight lang="vbnet">For iterator [ As datatype ] = startvalue To endvalue [ Step stepvalue ]
[ statement block ]
Next [ iterator ]
</syntaxhighlight>
<h3>[[While_loop|Do..Loop]]</h3>
Executes a block of statements while or until a condition is met.
<syntaxhighlight lang="vbnet">Do [ { Until | While } condition ]
[ statement block ]
Loop</syntaxhighlight>
or
<syntaxhighlight lang="vbnet">Do
[ statement block ]
Loop [ { Until | While } condition ]
</syntaxhighlight>
<h3>Intra-loop control</h3>
Continue While, Continue For and Continue Do
Prematurely re-enters a loop.<br>
<syntaxhighlight lang="vbnet">Continue {Do | For | While}</syntaxhighlight>
Exit While, Exit For and Exit Do
Prematurely breaks out of a loop.
<syntaxhighlight lang="vbnet">Exit {Do | For | While | Select }</syntaxhighlight>
<syntaxhighlight lang="vbnet">Exit {Sub | Function | Operator | Constructor | Destructor | Property }</syntaxhighlight>
<syntaxhighlight lang="vbnet">Exit {Do [, Do [ , ...] ] |
For [, For [ , ...] ] |
While [, While, [...] ] |
Select [, Select [ , ...] ] }</syntaxhighlight>
=={{header|Frink}}==
Line 239 ⟶ 425:
===For Loop===
A <CODE>for</CODE> loop is really a <CODE>foreach</CODE> loop that can work with range operators or iterate through various data structures. The <CODE>to</CODE> operator creates an enumerating expression that lazily steps through its range.
<
for i = 1 to 1000000
{
println[i]
}
</syntaxhighlight>
The <CODE>to</CODE> operator can be combined with a <CODE>step</CODE> statement:
<
for i = 1 to 1000000 step 3
println[i]
</syntaxhighlight>
As a <CODE>foreach</CODE> statement. The <CODE>for</CODE> construct can iterate over the elements of an array, set, dictionary, or enumerating expression.
<
for i = [2,3,7,9]
println[i]
</syntaxhighlight>
===Do...While Loop===
<
i=0
do
Line 265 ⟶ 452:
i = i+1
} while i<1000
</syntaxhighlight>
==[[Groovy]]==
Line 419 ⟶ 605:
The <tt>break</tt> statement will immediately terminate the current innermost <tt>for</tt>, <tt>while</tt>, <tt>repeat</tt>, <tt>if</tt>, <tt>case</tt> or <tt>switch</tt> without having to resort to a <tt>goto</tt>.
==[[Jinja]]==
===for===
<lang jinja>
print(Template("""{% for lang in ["Jinja", "Python", "Swift", "Nim"] %}
{{ loop.index }}) {{ lang }}
{%- endfor %}""").render())
</lang>
==[[Kabap]]==
There is no native loop command in Kabap, but labels, variables, jumps and conditional execution are supported which is enough to create a basic loop structure. Support for native loops is being prepared for the next major release.
===Basic loop===
<lang Kabap>
$i = 0;
:start;
// Your loop code here
$i = $i + 1;
if $i < 20;
goto start;
</lang>
==[[Logo]]==
Line 500 ⟶ 708:
Array.iteri</lang>
=={{header|Prolog}}==
There are three primitive methods of looping in Prolog: recursion, fail-driven loops, and repeat-driven loops.
<lang Prolog>% recursion as loop
print_each_element([]).
print_each_element([E|T]) :- writeln(E), print_each_element(T).
% fail-driven loop
fact(foo).
fact(bar).
fact(baz).
print_each_fact :-
( fact(X), writeln(X), fail
; true ).
% equivalently
%print_each_fact :- fact(X), writeln(X), fail.
%print_each_fact.
% repeat-driven loop
print_each_fact_again :-
repeat,
fact(X),
writeln(X),
X = baz,
!.
go :-
print_each_element([foo, bar, baz]),
print_each_fact,
print_each_fact_again.</lang>
Of the three recursion is the favoured approach as it requires no non-logical predicates and is thus easy to read in its declarative form.
The fail-driven loop form is a(n ab)use of the built-in backtracking mechanism of Prolog's reasoning engine. In the specific example provided, fact(X) will first succeed, binding "foo" to X. It will then write "foo" to the output (as a side effect of the writeln/1 predicate). It then hits the call to fail/0 which is a non-logical predicate which always fails and thus always triggers backtracking. On backtracking, the runtime will try fact(X) again and will find that it is true when X is bound to "bar". This will then print and backtrack again. A third time binds to and prints "baz". A fourth time will fail because there is no more solution to the goal "fact(X)". This triggers a further backtrack and a try on the second branch of the disjunction. That second branch invokes the true/0 predicate which always succeeds. This exits the query with an overall success.
The repeat-driven loop uses similar (ab)use of the backtracking mechanism. Instead of employing a predicate that always fails, however, it employs one that will always succeed: repeat/0. Thus, in this sample, fact(X) works as before, as does writeln(X), but the attempt to unify X with "baz" will fail for the first two attempts, causing the system to backtrack until it hits repeat. Since repeat always succeeds it drives the engine forward again, testing each fact in succession. Once X is unified with "baz" (which is to say once X contains the value "baz") the predicate carries on. The cut operator !/0, guarantees that the predicate won't be re-entered later.
As with any language permitting higher-order invocations, using the looping primitives directly as above is often not a desirable thing. Instead higher-order features would be used.
<lang Prolog>% using maplist/2 to replace explicit recursion on a list
print_each_element(L) :- maplist(writeln, L).
% using forall/2 to replace an explicit fail-driven loop
fact(foo).
fact(bar).
fact(baz).
print_each_fact() :- forall(fact(X), writeln(X)).</lang>
There are a myriad of such predicates available in a useful Prolog implementation (SWI-Prolog provides, non-exhaustively: include/3, exclude/3, partition/4-5, maplist/2-5, foldl/4-7, scanl/4-6, aggregate/3-4, aggregate_all/3-4, forall/2, findall/3-4, findnsols/4-5, bagof/3, setof/3, … just as the more fundamental wrappings.) If the provided predicates do not permit the kinds of functionality desired for common patterns, it is trivial to make a new one. As an illustration, this is the source code for forall/2:
<lang Prolog>:- meta_predicate forall(0,0).
forall(A, B) :- \+ (call(A), \+ call(B)).</lang>
=={{header|Pop11}}==
=== until ===
Line 661 ⟶ 924:
repeat <come_condition> until
<some_process>
=={{header|REXX}}==
===repeat===
This example shows how to perform a loop for one million times.
<lang rexx>n= 1000000
x= 1
y= 12
z= 0
do n
z=someFunction(z, x, y)
end /*n*/</lang> <br><br>
==[[Seed7]]==
Line 690 ⟶ 964:
writeln(stri);
end for;
==SETL4==
<lang setl4>
define('prime(n)set.this') :(prime.end)
* Tests if _n_ is a prime integer.
prime
n = integer(n) +n
eq(n,2) :s(return)
even(n) :s(freturn)
exists(new('iter 3 ' square.root(n) ' 2'), 'multiple(n,this)') :s(freturn)f(return)
prime.end
define('primes(n)set.this') :(primes.end)
* Returns set of primes less than _n_.
primes
primes = filter(new('iter 2 ' (n - 1)),'prime(this)') :(return)
primes = new('set')
iter = new('iter 2 ' (n - 1))
loop(iter)
primes.loop
this = next(iter) :f(return)
prime(this) add(primes,this) :(primes.loop)
primes.end
</lang>
==[[SIMPOL]]==
Line 738 ⟶ 1,046:
end while field =@= table.firstfield
end function fieldnames</lang>
=={{header|Sing}}==
<lang Sing>fn loops() void
{
// while: the condition must be strictly of boolean type
var idx = 0;
while (idx < 10) {
++idx;
}
// for in an integer range, the last value is excluded
// it is local to the loop and must not be previously declared
for (it in 0 : 10) {
}
// reverse direction
for (it in 10 : 0) {
}
// configurable step. The loop stops when it >= the final value
for (it in 0 : 100 step 3) {
}
// with an auxiliary counter. The counter start always at 0 and increments by one at each iteration
for (counter, it in 3450 : 100 step -22) {
}
// value assumes in turn all the values from array
var array [*]i32 = {0, 10, 100, 1000};
for (value in array) {
}
// as before with auxiliary counter
for (counter, value in array) {
}
}</lang>
==[[SNUSP]]==
Line 799 ⟶ 1,143:
0 [ dup . 1 + dup 101 = ] whileFalse
==[[Tern]]==
Tern has several distinct loop statements.
===Infinite Loop===
<lang tern>let v = 0;
loop {
println(v++);
}</lang>
===While Loop===
<lang tern>let v = 0;
while(v < 100) {
println(v++);
}</lang>
===For Loop===
<lang tern>for(let v = 0; v < 100; v++) {
println(v);
}</lang>
===For In Loop===
<lang tern>for(v in 0 to 99) {
println(v);
}</lang>
=={{header|Woma}}==
Woma is limited to for loops.
==Infinte Loop==
<lang woma>i<@>iter(int, 1)
print(i)
</lang>
===For Loop===
<lang woma>i<@>range(100)
print(i)
</lang>
|