Loops/Increment loop index within loop body: Difference between revisions

m
syntax highlighting fixup automation
(Loops/Increment loop index within loop body in Yabasic)
m (syntax highlighting fixup automation)
Line 58:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F is_prime(n)
L(x) (2, 3)
I n % x == 0
Line 77:
print(‘n = #2 #16’.format(n, i))
i += i - 1
i++</langsyntaxhighlight>
 
{{out}}
Line 101:
This task is a good example of the use of ED instruction to format a number.
For macro use (IF,DO,...), see [[360_Assembly_macros#360_Assembly_Structured_Macros|Structured Macros]].
<langsyntaxhighlight lang="360asm">* Loops/Increment loop index within loop body - 16/07/2018
LOOPILWB PROLOG
SR R6,R6 i=0
Line 173:
ZN DS CL20
REGEQU
END LOOPILWB</langsyntaxhighlight>
{{out}}
<pre style="height:40ex">
Line 221:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopinc64.s */
Line 471:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 520:
=={{header|Ada}}==
Ada does not allow the loop counter of a FOR loop to be modified in the loop. This example uses a simple Ada loop. The example also uses an Ada fixed decimal type to provide the comma insertion for the output.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO.Editing; use Ada.Text_IO.Editing;
Line 571:
end loop;
end Main;
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 620:
=={{header|ALGOL 68}}==
In Algol 68, the FOR loop counter cannot be modified in the loop. This uses a WHILE loop testing at the top but is otherwise largely a translation of the Kotlin entry.
<langsyntaxhighlight lang="algol68">BEGIN
# returns TRUE if n is prime, FALSE otherwise #
PROC is prime = ( LONG INT n )BOOL:
Line 654:
i +:= 1
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 703:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program loopinc96.s */
Line 1,200:
pop {r4,r5,lr} @ restaur registers
bx lr @ return
</syntaxhighlight>
</lang>
{{out}}
<Pre>
Line 1,250:
=={{header|Arturo}}==
{{trans|Python}}
<langsyntaxhighlight lang="rebol">i: 42
n: 0
 
Line 1,262:
i: i + 1
]
]</langsyntaxhighlight>
{{out}}
<pre>n = 1 43
Line 1,308:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">i:= 42, n:= 1, result := ""
while (n<43){
if isPrime(i)
Line 1,328:
}
return true
}</langsyntaxhighlight>
{{out}}
<pre>1: 43
Line 1,374:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f LOOPS_INCREMENT_LOOP_INDEX_WITHIN_LOOP_BODY.AWK
BEGIN {
Line 1,399:
return(1)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,448:
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256">function isPrime(number)
if (number % 2 = 0) or (number % 3 = 0) then return false
lim = sqr(number)
Line 1,469:
i += 1
end while
end</langsyntaxhighlight>
 
 
Line 1,477:
 
The 'thousands separator' aspect (using the ' flag in printf and setting the locale appropriately) works fine when compiled with gcc on Ubuntu 14.04 but may not work on some other systems as this is not a standard flag.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <locale.h>
 
Line 1,506:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,514:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Globalization;
Line 1,549:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,597:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include "stdafx.h"
#include <iostream>
Line 1,635:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defun primep (n) ; https://stackoverflow.com/questions/15817350/
(cond ((= 2 n) t) ; Hard-code "2 is a prime"
Line 1,656:
(format t "~&~5<~d~;->~>~20<~:d~>" c i) ; Display count of primes found and the prime
(incf i (decf i))))) ; Increment index to previous index plus the prime
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,705:
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Increment_loop_index_within_loop_body;
 
Line 1,760:
end;
readln;
end.</langsyntaxhighlight>
{{out}}
Same of [[#C#]].
Line 1,766:
=={{header|Dyalect}}==
 
<langsyntaxhighlight Dyalectlang="dyalect">func isPrime(number) {
if number <= 1 {
return false
Line 1,796:
}
i += 1
}</langsyntaxhighlight>
 
Output:
Line 1,845:
=={{header|F_Sharp|F#}}==
This task uses [http://www.rosettacode.org/wiki/Extensible_prime_generator#The_function Extensible Prime Generator (F#)]
<langsyntaxhighlight lang="fsharp">
// Well I don't do loops. Nigel Galloway: March 17th., 2019. Let me try to explain where the loopy variables are, for the imperatively constrained.
// cUL allows me to claim the rather trivial extra credit (commas in the numbers)
Line 1,855:
// unfold is sort of a loop with fG as an internal loop incremented by the exit value of the internal loop in this case.
Seq.unfold(fun n->let n=fG n in Some(n,n+n)) 42UL|>Seq.take 42|>Seq.iteri(fun n g->printfn "%2d -> %s" (n+1) (cUL g))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,905:
Explicit loop indices are non-idiomatic, but Factor is certainly capable of using them. Factor has a for loop near-equivalent, <code><range> [ ] each</code>, but since it doesn't mesh well with mutation, a while loop is used.
=== Using two numbers on the data stack ===
<langsyntaxhighlight lang="factor">USING: formatting kernel math math.primes
tools.memory.private ;
IN: rosetta-code.loops-inc-body
Line 1,919:
[ 1 + ] dip
] while
2drop</langsyntaxhighlight>
=== Using lexical variables ===
Factor provides lexical variables for situations where they improve readability.
<langsyntaxhighlight lang="factor">USING: formatting kernel math math.primes
tools.memory.private ;
IN: rosetta-code.loops-inc-body
Line 1,937:
i 1 + i!
] while
]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,986:
=={{header|Fortran}}==
Fortran does not allow to modify the index inside the loop.
<langsyntaxhighlight lang="fortran">do i=1,10
write(*,*) i
i=i+1
end do</langsyntaxhighlight>
<pre>
Error - I is currently being used as a DO or implied DO control variable
Line 1,996:
 
===Fortran 95===
<langsyntaxhighlight lang="fortran">! Loops Increment loop index within loop body - 17/07/2018
integer*8 n
imax=42
Line 2,030:
return
EndIf
EndFunction</langsyntaxhighlight>
{{out}}
<pre style="height:60ex">
Line 2,079:
===Fortran IV===
The limit is set to 25 due to the size of integer in Fortran IV.
<langsyntaxhighlight lang="fortran">C LOOPS INCREMENT LOOP INDEX WITHIN LOOP BODY - 17/07/2018
IMAX=25
I=0
Line 2,110:
50 ISPRIME=1
RETURN
END</langsyntaxhighlight>
{{out}}
<pre style="height:60ex">
Line 2,141:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 18-01-2019
' compile with: fbc -s console
 
Line 2,178:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre style="height:40ex">n = 1 43
Line 2,227:
 
The 'thousands separator' aspect is dealt with by a couple of external packages (in the 'import' declarations) which can be installed using 'go get'.
<langsyntaxhighlight lang="go">package main
 
import(
Line 2,266:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,275:
=={{header|Haskell}}==
No index mutations or loops. Recursion is used.
<langsyntaxhighlight lang="haskell">import Data.List
import Control.Monad (guard)
 
Line 2,301:
display (i, p) = show i ++ " " ++ digitGroup p
 
main = mapM_ (putStrLn . display) $ take 42 $ showPrime 42 1</langsyntaxhighlight>
{{out}}
<pre>
Line 2,350:
And for minor variation, we could import isPrime from Data.Numbers.Primes, and define the comma-grouping of large integers in terms of chunksof:
 
<langsyntaxhighlight lang="haskell">import Data.Numbers.Primes
import Data.List (intercalate)
import Data.List.Split (chunksOf)
Line 2,368:
 
main :: IO ()
main = mapM_ (putStrLn . showPair) (take 42 $ series 42 1)</langsyntaxhighlight>
 
=={{header|Haxe}}==
Haxe's for-loop does allow the index to be modified in the body of the loop, so a while-loop is used instead.
<langsyntaxhighlight lang="haxe">using StringTools;
import haxe.Int64;
 
Line 2,408:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,458:
=={{header|J}}==
Fun with j. The verb tacit_loop implements the computation.
<syntaxhighlight lang="j">
<lang j>
tacit_loop =: _1&(>:@:{`[`]})@:(, (1&p: # _1 2&p.)@:{:)@:]^:(0 ~: (>: #))^:_ x:
</syntaxhighlight>
</lang>
Now derive it from the python solution. The monadic verb loop fairly straightforwardly matches the python solution except that loop returns the vector of computed values rather than displays them.
<syntaxhighlight lang="j">
<lang j>
isPrime =: 1&p:
assert 1 1 0 -: isPrime 2 3 4 NB. test and example
Line 2,478:
n
)
</syntaxhighlight>
</lang>
Store the vector of indexes using its tail as the current index, removing the `n' variable. In doing so the last item of `i' is not part of the solution, hence change less than to less or equal, and discard the tail value. Also extract the conversion to extended precision x: .
<syntaxhighlight lang="j">
<lang J>
loop =: verb define@:x:
i =. y
Line 2,491:
}: i
)
</syntaxhighlight>
</lang>
 
Replace the "if" statement with a computation. This one works by appending onto the solution vector isPrime copies of the proposed new index.
<syntaxhighlight lang="j">
<lang J>
loop =: verb define@:x:
i =. y
Line 2,503:
}: i
)
</syntaxhighlight>
</lang>
Names are an issue brought forth in the j forums. Names have most meaning to the person who wrote them, so there's a bit of J philosophy that says "show the code". J doesn't enforce "code only", and definitions can encapsulate useful chunks of code. If the names I've chosen don't work in your experience or language you could replace them with `a' and `b'.
<syntaxhighlight lang="j">
<lang J>
save_if_prime =: , (isPrime # _1 2&p.)@:{:
increment_tail =: _1&(>:@:{`[`]})
Line 2,517:
}: i
)
</syntaxhighlight>
</lang>
Why make two assignments when j can increment at save?
<syntaxhighlight lang="j">
<lang J>
loop =: verb define@:x:
i =. y
Line 2,527:
}: i
)
</syntaxhighlight>
</lang>
Next replace the while loop with double application of J's generalized power conjunction.
<syntaxhighlight lang="j">
<lang J>
While =: conjunction def 'u^:(0~:v)^:_'
 
Line 2,536:
}: increment_tail@:save_if_prime While(y >: #) i
)
</syntaxhighlight>
</lang>
By inspection the variable `i' doesn't contribute anything useful whatsoever. The verb's argument, y, remains.
Finally, implemented as an hook [http://www.jsoftware.com/help/dictionary/dictf.htm verb trains] with 'y' and `i' as left ([) and right (]) arguments the complete definitions for tacit_loop are
<syntaxhighlight lang="j">
<lang J>
isPrime =: 1&p:
save_if_prime =: , (isPrime # _1 2&p.)@:{:
Line 2,545:
While =: conjunction def 'u^:(0~:v)^:_'
tacit_loop =: [: }: (increment_tail@:save_if_prime@:]While(>: #) x:)
</syntaxhighlight>
</lang>
Include the index numbers with demonstration:
<syntaxhighlight lang="j">
<lang J>
9!:37 ] 0 2048 0 222 NB. output control permit lines of 2^11 columns
 
Line 2,559:
[: }: (_1&(>:@:{`[`]})@:(, (1&p: # _1 2&p.)@:{:)@:]^:(0 ~: (>: #))^:_ x:)
</syntaxhighlight>
</lang>
If the loop must require the output side effect, this save_if_prime definition does the trick. Without the output hook it is probably more efficient than the copying version because it evaluates the hook <pre>(, _1 2&p.@:{:)</pre> only when isPrime is true.
<syntaxhighlight lang="j">
<lang J>
extra_credit =: ([: }. ,@(',' ,.~ _3 [\ ])&.|.@:":)&>
show =: [ ([: echo@:deb@:({. , ' ' , {:)@:extra_credit # , {:)
Line 2,608:
41 49,752,014,150,467
42 99,504,028,301,131
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
The following uses a 'for' rather than a 'do/while' loop but otherwise is similar to the Kotlin
entry.
<langsyntaxhighlight lang="java">public class LoopIncrementWithinBody {
 
static final int LIMIT = 42;
Line 2,640:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,657:
This entry uses the jq implementation of is_prime as shown at
[[Erd%C5%91s-primes#jq]].
<langsyntaxhighlight lang="jq">{i:42, count:0}
| while( .count <= 42;
.emit = null
Line 2,668:
else .
end )
| select(.emit).emit</langsyntaxhighlight>
{{out}}
<pre>
Line 2,718:
=={{header|Julia}}==
Julia's <code>for</code> loop iterator is an iterator type which cannot be incremented as a simple variable would to change looping.
<langsyntaxhighlight lang="julia">using Primes, Formatting
 
function doublemyindex(n=42)
Line 2,735:
 
doublemyindex()
</langsyntaxhighlight> {{output}} <pre>
The index is 1 and 43 is prime.
The index is 2 and 89 is prime.
Line 2,784:
 
So instead we use a do/while loop here which has no such restrictions.
<langsyntaxhighlight lang="scala">// version 1.2.60
 
fun isPrime(n: Long): Boolean {
Line 2,811:
}
while (n < 42)
}</langsyntaxhighlight>
{{out}}
<pre style="height:35ex">n = 1 43
Line 2,862:
The following version uses a tail recursive function rather than a while loop to achieve the same effect:
 
<langsyntaxhighlight lang="scala">// version 1.2.60
 
fun isPrime(n: Long): Boolean {
Line 2,891:
fun main(args: Array<String>) {
loop(42, 0)
}</langsyntaxhighlight>
 
{{out}}
Line 2,899:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 2,934:
(( i+=$i ))
fi
done</langsyntaxhighlight>
{{out}}<pre>
43 is prime, 1 primes found(so far)
Line 2,980:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">-- Returns boolean indicate whether x is prime
function isPrime (x)
if x < 2 then return false end
Line 3,000:
end
i = i + 1
end</langsyntaxhighlight>
{{out}}
<pre>n = 1 43
Line 3,046:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Function IsPrime (x) {
Line 3,077:
}
CheckIt
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,086:
=={{header|Maple}}==
A translation of Kotlin entry
<langsyntaxhighlight Maplelang="maple">i := 42:
count := 0:
while(count < 42) do
Line 3,095:
i := 2*i -1:
end if:
end do:</langsyntaxhighlight>
{{Out|Output}}
<pre>n=1 43
Line 3,141:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">{i, n} = {42, 0};
While[n < 42,
If[PrimeQ[i],
Line 3,148:
];
i++;
]</langsyntaxhighlight>
{{out}}
<pre>n=0 43
Line 3,195:
=={{header|Microsoft Small Basic}}==
Small Basic allows to modify the index inside the loop.
<langsyntaxhighlight lang="smallbasic">'Loops Increment loop index within loop body - 16/07/2018
imax=42
i=0
Line 3,251:
nn=Text.GetSubText(space,1,Text.GetLength(space)-Text.GetLength(nn))+nn
ret_format_n=nn
EndSub 'format_n</langsyntaxhighlight>
{{out}}
<pre style="height:60ex">
Line 3,300:
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight Nanoquerylang="nanoquery">limit = 42
 
def isPrime(n)
Line 3,327:
i += i - 1
end
end</langsyntaxhighlight>
 
{{out}}
Line 3,374:
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="newlisp">
#! /usr/local/bin/newlisp
 
Line 3,412:
 
(exit)
</syntaxhighlight>
</lang>
 
<pre>
Line 3,462:
=={{header|Nim}}==
In Nim, loop index is read-only, so we have to use a normal variable and increment it as needed.
<langsyntaxhighlight lang="nim">
import strformat
from strutils import insertSep
Line 3,491:
 
main()
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:50ex">
Line 3,542:
{{trans|Kotlin}}
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw(is_prime);
 
$i = 42;
Line 3,558:
$s =~ s/,$//;
$s = reverse $s;
}</langsyntaxhighlight>
{{out}}
<pre style="height:30ex"> 1 43
Line 3,605:
=={{header|Phix}}==
Phix does not allow for loop variables to be modified, so we must use a while loop and manual increment for this sort of thing.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">atom</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">42</span> <span style="color: #008080;">do</span>
Line 3,615:
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,664:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight Pythonlang="python">def isPrime(n):
for x in 2, 3:
if not n % x:
Line 3,683:
print('n = {:2} {:20,}'.format(n, i))
i += i - 1
i += 1</langsyntaxhighlight>
{{out}}
<pre>n = 1 43
Line 3,732:
This task is defined in terms of procedural 'loops', which can generally be understood in functional terms as implementations of folds or maps. An analogous functional construction here might be a non-finite generator, or the iterative application of a function (over a tuple of values) to a seed value, for example:
 
<langsyntaxhighlight lang="python">'''Loops/Increment loop index within loop body.'''
 
from itertools import islice, takewhile
Line 3,879:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre> 1 -> 43
Line 3,925:
=={{header|R}}==
R cannot complete this task with a for loop. See https://stackoverflow.com/a/5913329/ . Instead, we must go down the same path as the Kotlin solution. Because it is sufficient for numbers this small, we will save ourselves some work and use the gmp library's isprime function for checking if a number is prime.
<langsyntaxhighlight lang="rsplus">i <- 42
primeCount <- 0
while(primeCount < 42)
Line 3,937:
}
i <- i + 1
}</langsyntaxhighlight>
{{Out}}
<pre>Prime count: 1; The prime just found was: 43
Line 3,986:
Racket's <code>for</code> doesn't allow modification of index on the fly. The usual idiom for writing this kind of loop is to use named let, as shown here.
 
<langsyntaxhighlight lang="racket">#lang racket
 
(require math/number-theory)
Line 4,004:
[(prime? x) (printf "~a: ~a\n" (add1 cnt) (comma x))
(loop (* 2 x) (add1 cnt))]
[else (loop (add1 x) cnt)]))</langsyntaxhighlight>
 
{{out}}
Line 4,058:
The ''best'' way is probably to not use an explicit loop. Just calculate the sequence directly.
 
<syntaxhighlight lang="raku" perl6line># the actual sequence logic
my @seq = grep *.is-prime, (42, { .is-prime ?? $_+<1 !! $_+1 } … *);
 
# display code
say (1+$_).fmt("%-4s"), @seq[$_].flip.comb(3).join(',').flip.fmt("%20s") for ^42;</langsyntaxhighlight>
{{out}}
<pre>1 43
Line 4,108:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX pgm displays primes found: starting Z at 42, if Z is a prime, add Z, else add 1.*/
numeric digits 20; d=digits() /*ensure enough decimal digits for Z. */
parse arg limit . /*obtain optional arguments from the CL*/
Line 4,127:
do j=5 by 6 until j*j>#; if # // j==0 | # // (J+2)==0 then return 0
end /*j*/ /* ___ */
return 1 /*Exceeded √ # ? Then # is prime. */</langsyntaxhighlight>
{{out|output}}
<pre>
Line 4,175:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Loops/Increment loop index within loop body
 
Line 4,189:
i = i + 1
end
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,236:
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
require 'prime'
Line 4,252:
end
end
</syntaxhighlight>
</lang>
Output :
<pre>
Line 4,304:
So instead we use tail recursion here which, with the use of immutable variables and no side effects, has no such restrictions, and we are save.
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/4HJPkBM/1 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/yzqldLOuRriR6ojqLKaYPQ Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">import scala.annotation.tailrec
 
object LoopIncrementWithinBody extends App {
Line 4,324:
 
loop(limit, offset)
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func boolean: isPrime (in integer: number) is func
Line 4,357:
end if;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,407:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">numFound := 0.
idx := 42.
[:exit |
Line 4,417:
numFound == 42 ifTrue:exit
].
] loopWithExit.</langsyntaxhighlight>
Note: above code uses a public domain printf goodie which is part of many Smalltalk's base libraries; if not present in a particular dialect, use regular print/display/transcribe or whatever is available.
{{out}}
Line 4,443:
 
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
<lang Standard ML>
fun until done change dolast x =
if done x
Line 4,475:
 
val printp = fn clist:(int*IntInf.int) list =>
List.app (fn i=>print ((Int.toString (#1 i) )^" : "^ (IntInf.toString (#2 i) )^"\n")) clist ; </langsyntaxhighlight>
call <pre>
printp (loop ()) ;
Line 4,525:
 
Tcl allows modifying the loop variable. Everything can be implemented straightforward.
<langsyntaxhighlight lang="tcl">proc isPrime n {
if {[expr $n % 2] == 0} {
return [expr $n == 2]
Line 4,548:
incr i [expr $i -1]
}
}</langsyntaxhighlight>
{{Out}}
<pre>n=1, i=43
Line 4,597:
{{trans|Visual Basic .NET}}
{{works with|VBA|VBA Excel 2013}}
<langsyntaxhighlight lang="vb"> Sub Main()
'Loops Increment loop index within loop body - 17/07/2018
Dim imax, i As Integer
Line 4,638:
Function RightX(c, n)
RightX = Right(Space(n) & c, n)
End Function 'RightX</langsyntaxhighlight>
{{out}}
<pre style="height:60ex">
Line 4,688:
{{trans|Visual Basic}}
{{works with|Visual Basic .NET|2013}}
<langsyntaxhighlight lang="vbnet">Module LoopsIliwlb
 
Sub Main()
Line 4,729:
End Function
 
End Module</langsyntaxhighlight>
{{out}}
<pre style="height:60ex">i= 1 : 43
Line 4,776:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="vlang">fn is_prime(n u64) bool {
if n % 2 == 0 {
return n == 2
Line 4,805:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,815:
{{libheader|Wren-fmt}}
Although it might appear as though one can change the index variable within a ''for'' loop, it does in fact change a local copy of the variable and the iteration is not affected at all. Consequently, the only way to complete this task in Wren is to use a ''while'' loop.
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var isPrime = Fn.new { |n|
Line 4,840:
}
i = i + 1
}</langsyntaxhighlight>
 
{{out}}
Line 4,889:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang="yabasic">i = 42
counter = 0
while counter < 42
Line 4,910:
wend
return True
end sub</langsyntaxhighlight>
 
=={{header|zkl}}==
Uses libGMP (GNU MP Bignum Library) for easy prime detection
rather than write that bit of code and pollute this solution.
<langsyntaxhighlight lang="zkl">var [const] BN=Import("zklBigNum"); // libGMP
n,p := 1,BN(42);
do{
if(p.probablyPrime()){ println("n = %2d %,20d".fmt(n,p)); p.add(p); n+=1; }
p.add(1);
}while(n<=42);</langsyntaxhighlight>
zkl loop variables are iterators that don't allow direct manipulation of
their underlying source. The compiler names these iterators __<index>Walker.
However, by using the look ahead stack, we can keep the iterator from
advancing through the source.
<langsyntaxhighlight lang="zkl">p:=BN(42);
foreach n in ([1..42]){
if(p.probablyPrime()){ println("n = %2d %,20d".fmt(n,p)); p.add(p); }
else{ p.add(1); __nWalker.push(n); } // p not prime, don't advance n
}</langsyntaxhighlight>
{{out}}
<pre style="height:35ex">
10,333

edits