Loops/Increment loop index within loop body: Difference between revisions
Loops/Increment loop index within loop body (view source)
Revision as of 21:23, 27 August 2022
, 1 year agosyntax highlighting fixup automation
(Loops/Increment loop index within loop body in Yabasic) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 58:
{{trans|Python}}
<
L(x) (2, 3)
I n % x == 0
Line 77:
print(‘n = #2 #16’.format(n, i))
i += i - 1
i++</
{{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]].
<
LOOPILWB PROLOG
SR R6,R6 i=0
Line 173:
ZN DS CL20
REGEQU
END LOOPILWB</
{{out}}
<pre style="height:40ex">
Line 221:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight 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>
{{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.
<
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>
{{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.
<
# returns TRUE if n is prime, FALSE otherwise #
PROC is prime = ( LONG INT n )BOOL:
Line 654:
i +:= 1
OD
END</
{{out}}
<pre>
Line 703:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program loopinc96.s */
Line 1,200:
pop {r4,r5,lr} @ restaur registers
bx lr @ return
</syntaxhighlight>
{{out}}
<Pre>
Line 1,250:
=={{header|Arturo}}==
{{trans|Python}}
<
n: 0
Line 1,262:
i: i + 1
]
]</
{{out}}
<pre>n = 1 43
Line 1,308:
=={{header|AutoHotkey}}==
<
while (n<43){
if isPrime(i)
Line 1,328:
}
return true
}</
{{out}}
<pre>1: 43
Line 1,374:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f LOOPS_INCREMENT_LOOP_INDEX_WITHIN_LOOP_BODY.AWK
BEGIN {
Line 1,399:
return(1)
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,448:
=={{header|BASIC256}}==
<
if (number % 2 = 0) or (number % 3 = 0) then return false
lim = sqr(number)
Line 1,469:
i += 1
end while
end</
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.
<
#include <locale.h>
Line 1,506:
}
return 0;
}</
{{out}}
Line 1,514:
=={{header|C sharp|C#}}==
<
using System;
using System.Globalization;
Line 1,549:
}
}
}</
{{out}}
<pre>
Line 1,597:
=={{header|C++}}==
<
#include "stdafx.h"
#include <iostream>
Line 1,635:
}
return 0;
}</
=={{header|Common 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>
{{out}}
<pre>
Line 1,705:
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Increment_loop_index_within_loop_body;
Line 1,760:
end;
readln;
end.</
{{out}}
Same of [[#C#]].
Line 1,766:
=={{header|Dyalect}}==
<
if number <= 1 {
return false
Line 1,796:
}
i += 1
}</
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#)]
<
// 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>
{{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 ===
<
tools.memory.private ;
IN: rosetta-code.loops-inc-body
Line 1,919:
[ 1 + ] dip
] while
2drop</
=== Using lexical variables ===
Factor provides lexical variables for situations where they improve readability.
<
tools.memory.private ;
IN: rosetta-code.loops-inc-body
Line 1,937:
i 1 + i!
] while
]</
{{out}}
<pre>
Line 1,986:
=={{header|Fortran}}==
Fortran does not allow to modify the index inside the loop.
<
write(*,*) i
i=i+1
end do</
<pre>
Error - I is currently being used as a DO or implied DO control variable
Line 1,996:
===Fortran 95===
<
integer*8 n
imax=42
Line 2,030:
return
EndIf
EndFunction</
{{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.
<
IMAX=25
I=0
Line 2,110:
50 ISPRIME=1
RETURN
END</
{{out}}
<pre style="height:60ex">
Line 2,141:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 2,178:
Print : Print "hit any key to end program"
Sleep
End</
{{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'.
<
import(
Line 2,266:
}
}
}</
{{out}}
Line 2,275:
=={{header|Haskell}}==
No index mutations or loops. Recursion is used.
<
import Control.Monad (guard)
Line 2,301:
display (i, p) = show i ++ " " ++ digitGroup p
main = mapM_ (putStrLn . display) $ take 42 $ showPrime 42 1</
{{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:
<
import Data.List (intercalate)
import Data.List.Split (chunksOf)
Line 2,368:
main :: IO ()
main = mapM_ (putStrLn . showPair) (take 42 $ series 42 1)</
=={{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.
<
import haxe.Int64;
Line 2,408:
}
}
}</
{{out}}
Line 2,458:
=={{header|J}}==
Fun with j. The verb tacit_loop implements the computation.
<syntaxhighlight lang="j">
tacit_loop =: _1&(>:@:{`[`]})@:(, (1&p: # _1 2&p.)@:{:)@:]^:(0 ~: (>: #))^:_ x:
</syntaxhighlight>
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">
isPrime =: 1&p:
assert 1 1 0 -: isPrime 2 3 4 NB. test and example
Line 2,478:
n
)
</syntaxhighlight>
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">
loop =: verb define@:x:
i =. y
Line 2,491:
}: i
)
</syntaxhighlight>
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">
loop =: verb define@:x:
i =. y
Line 2,503:
}: i
)
</syntaxhighlight>
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">
save_if_prime =: , (isPrime # _1 2&p.)@:{:
increment_tail =: _1&(>:@:{`[`]})
Line 2,517:
}: i
)
</syntaxhighlight>
Why make two assignments when j can increment at save?
<syntaxhighlight lang="j">
loop =: verb define@:x:
i =. y
Line 2,527:
}: i
)
</syntaxhighlight>
Next replace the while loop with double application of J's generalized power conjunction.
<syntaxhighlight lang="j">
While =: conjunction def 'u^:(0~:v)^:_'
Line 2,536:
}: increment_tail@:save_if_prime While(y >: #) i
)
</syntaxhighlight>
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">
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>
Include the index numbers with demonstration:
<syntaxhighlight 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>
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">
extra_credit =: ([: }. ,@(',' ,.~ _3 [\ ])&.|.@:":)&>
show =: [ ([: echo@:deb@:({. , ' ' , {:)@:extra_credit # , {:)
Line 2,608:
41 49,752,014,150,467
42 99,504,028,301,131
</syntaxhighlight>
=={{header|Java}}==
The following uses a 'for' rather than a 'do/while' loop but otherwise is similar to the Kotlin
entry.
<
static final int LIMIT = 42;
Line 2,640:
}
}
}</
{{out}}
Line 2,657:
This entry uses the jq implementation of is_prime as shown at
[[Erd%C5%91s-primes#jq]].
<
| while( .count <= 42;
.emit = null
Line 2,668:
else .
end )
| select(.emit).emit</
{{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.
<
function doublemyindex(n=42)
Line 2,735:
doublemyindex()
</
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.
<
fun isPrime(n: Long): Boolean {
Line 2,811:
}
while (n < 42)
}</
{{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:
<
fun isPrime(n: Long): Boolean {
Line 2,891:
fun main(args: Array<String>) {
loop(42, 0)
}</
{{out}}
Line 2,899:
=={{header|Ksh}}==
<
#!/bin/ksh
Line 2,934:
(( i+=$i ))
fi
done</
{{out}}<pre>
43 is prime, 1 primes found(so far)
Line 2,980:
=={{header|Lua}}==
<
function isPrime (x)
if x < 2 then return false end
Line 3,000:
end
i = i + 1
end</
{{out}}
<pre>n = 1 43
Line 3,046:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Function IsPrime (x) {
Line 3,077:
}
CheckIt
</syntaxhighlight>
{{out}}
Line 3,086:
=={{header|Maple}}==
A translation of Kotlin entry
<
count := 0:
while(count < 42) do
Line 3,095:
i := 2*i -1:
end if:
end do:</
{{Out|Output}}
<pre>n=1 43
Line 3,141:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
While[n < 42,
If[PrimeQ[i],
Line 3,148:
];
i++;
]</
{{out}}
<pre>n=0 43
Line 3,195:
=={{header|Microsoft Small Basic}}==
Small Basic allows to modify the index inside the loop.
<
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</
{{out}}
<pre style="height:60ex">
Line 3,300:
=={{header|Nanoquery}}==
{{trans|Java}}
<
def isPrime(n)
Line 3,327:
i += i - 1
end
end</
{{out}}
Line 3,374:
=={{header|NewLISP}}==
<
#! /usr/local/bin/newlisp
Line 3,412:
(exit)
</syntaxhighlight>
<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.
<
import strformat
from strutils import insertSep
Line 3,491:
main()
</syntaxhighlight>
{{out}}
<pre style="height:50ex">
Line 3,542:
{{trans|Kotlin}}
{{libheader|ntheory}}
<
$i = 42;
Line 3,558:
$s =~ s/,$//;
$s = reverse $s;
}</
{{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.
<!--<
<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>
<!--</
{{out}}
<pre>
Line 3,664:
=={{header|Python}}==
===Procedural===
<
for x in 2, 3:
if not n % x:
Line 3,683:
print('n = {:2} {:20,}'.format(n, i))
i += i - 1
i += 1</
{{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:
<
from itertools import islice, takewhile
Line 3,879:
# MAIN ---
if __name__ == '__main__':
main()</
{{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.
<
primeCount <- 0
while(primeCount < 42)
Line 3,937:
}
i <- i + 1
}</
{{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.
<
(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)]))</
{{out}}
Line 4,058:
The ''best'' way is probably to not use an explicit loop. Just calculate the sequence directly.
<syntaxhighlight lang="raku"
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;</
{{out}}
<pre>1 43
Line 4,108:
=={{header|REXX}}==
<
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. */</
{{out|output}}
<pre>
Line 4,175:
=={{header|Ring}}==
<
# Project : Loops/Increment loop index within loop body
Line 4,189:
i = i + 1
end
</syntaxhighlight>
Output:
<pre>
Line 4,236:
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
require 'prime'
Line 4,252:
end
end
</syntaxhighlight>
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)].
<
object LoopIncrementWithinBody extends App {
Line 4,324:
loop(limit, offset)
}</
=={{header|Seed7}}==
<
const func boolean: isPrime (in integer: number) is func
Line 4,357:
end if;
end for;
end func;</
{{out}}
Line 4,407:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<
idx := 42.
[:exit |
Line 4,417:
numFound == 42 ifTrue:exit
].
] loopWithExit.</
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">
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 ; </
call <pre>
printp (loop ()) ;
Line 4,525:
Tcl allows modifying the loop variable. Everything can be implemented straightforward.
<
if {[expr $n % 2] == 0} {
return [expr $n == 2]
Line 4,548:
incr i [expr $i -1]
}
}</
{{Out}}
<pre>n=1, i=43
Line 4,597:
{{trans|Visual Basic .NET}}
{{works with|VBA|VBA Excel 2013}}
<
'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</
{{out}}
<pre style="height:60ex">
Line 4,688:
{{trans|Visual Basic}}
{{works with|Visual Basic .NET|2013}}
<
Sub Main()
Line 4,729:
End Function
End Module</
{{out}}
<pre style="height:60ex">i= 1 : 43
Line 4,776:
=={{header|Vlang}}==
{{trans|go}}
<
if n % 2 == 0 {
return n == 2
Line 4,805:
}
}
}</
{{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.
<
var isPrime = Fn.new { |n|
Line 4,840:
}
i = i + 1
}</
{{out}}
Line 4,889:
=={{header|Yabasic}}==
<
counter = 0
while counter < 42
Line 4,910:
wend
return True
end sub</
=={{header|zkl}}==
Uses libGMP (GNU MP Bignum Library) for easy prime detection
rather than write that bit of code and pollute this solution.
<
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);</
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.
<
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
}</
{{out}}
<pre style="height:35ex">
|