/* ARM assembly Raspberry PI  */
/*  program loopstep2.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
.equ MAXI,   20
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessResult:  .ascii "Counter = "      @ message result
sMessValeur:   .fill 12, 1, ' '
                   .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                @ entry of program
    push {fp,lr}      @ saves 2 registers
    mov r4,#0
1:    @ begin loop
    mov r0,r4
    ldr r1,iAdrsMessValeur     @ display value
    bl conversion10             @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    add r4,#2                   @ increment counter by 2
    cmp r4,#MAXI              @
    ble 1b                @ loop

100:   @ standard end of the program
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    svc #0                       @ perform the system call

iAdrsMessValeur:          .int sMessValeur
iAdrszMessResult:         .int szMessResult
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}      @ save  registres
    mov r2,#0                  @ counter length
1:      @ loop length calculation
    ldrb r1,[r0,r2]           @ read octet start position + index
    cmp r1,#0                  @ if 0 its over
    addne r2,r2,#1            @ else add 1 in the length
    bne 1b                    @ and loop
                                @ so here r2 contains the length of the message
    mov r1,r0        			@ address message in r1
    mov r0,#STDOUT      		@ code to write to the standard output Linux
    mov r7, #WRITE             @ code call system "write"
    svc #0                      @ call systeme
    pop {r0,r1,r2,r7,lr}        @ restaur des  2 registres */
    bx lr                       @ return
/******************************************************************/
/*     Converting a register to a decimal                                 */
/******************************************************************/
/* r0 contains value and r1 address area   */
conversion10:
    push {r1-r4,lr}    @ save registers
    mov r3,r1
    mov r2,#10

1:	   @ start loop
    bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48        @ digit
    strb r1,[r3,r2]  @ store digit on area
    sub r2,#1         @ previous position
    cmp r0,#0         @ stop if quotient = 0 */
    bne 1b	          @ else loop
    @ and move spaces in first on area
    mov r1,#' '   @ space
2:
    strb r1,[r3,r2]  @ store space in area
    subs r2,#1       @ @ previous position
    bge 2b           @ loop if r2 >= zéro

100:
    pop {r1-r4,lr}    @ restaur registres
    bx lr	          @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
    push {r2-r4}   /* save registers  */
    mov r4,r0
    mov r3,#0x6667   @ r3 <- magic_number  lower
    movt r3,#0x6666  @ r3 <- magic_number  upper
    smull r1, r2, r3, r0   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
    mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */
    mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */
    add r0, r2, r1         /* r0 <- r2 + r1 */
    add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */
    sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */
    pop {r2-r4}
    bx lr                  /* leave function */
/***************************************************/
/* integer division unsigned                       */
/***************************************************/
division:
    /* r0 contains dividend */
    /* r1 contains divisor */
    /* r2 returns quotient */
    /* r3 returns remainder */
    push {r4, lr}
    mov r2, #0                @ init quotient
    mov r3, #0                @ init remainder
    mov r4, #32               @ init counter bits
    b 2f
1:          @ loop
    movs r0, r0, LSL #1     @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
    adc r3, r3, r3           @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C
    cmp r3, r1               @ compute r3 - r1 and update cpsr
    subhs r3, r3, r1        @ if r3 >= r1 (C=1) then r3 ? r3 - r1
    adc r2, r2, r2           @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
    subs r4, r4, #1          @ r4 <- r4 - 1
    bpl 1b                  @ if r4 >= 0 (N=0) then loop
    pop {r4, lr}
    bx lr


/* Loops/Nested in Jsish */
Math.srand(0);
var nrows = Math.floor(Math.random() * 4) + 4;
var ncols = Math.floor(Math.random() * 6) + 6;

var matrix = new Array(nrows).fill(0).map(function(v, i, a):array { return new Array(ncols).fill(0); } );

var i,j;
for (i = 0; i < nrows; i++) for (j = 0; j < ncols; j++) matrix[i][j] = Math.floor(Math.random() * 20) + 1;

/* Labelled break point */
outer_loop:
for (i in matrix) {
    printf("row %d:", i);
    for (j in matrix[i]) {
        printf(" %d", matrix[i][j]);
        if (matrix[i][j] == 20) {
            printf("\n");
            break outer_loop;
        }
    }
    printf("\n");
}
puts(matrix);

/*
=!EXPECTSTART!=
row 0: 2 18 12 16 14 8 18 15 9 8
row 1: 15 6 8 16 17 12 15 2 10 3
row 2: 11 8 12 20
[ [ 2, 18, 12, 16, 14, 8, 18, 15, 9, 8 ],
  [ 15, 6, 8, 16, 17, 12, 15, 2, 10, 3 ],
  [ 11, 8, 12, 20, 18, 4, 6, 6, 19, 9 ],
  [ 16, 3, 2, 19, 1, 4, 8, 4, 11, 18 ] ]
=!EXPECTEND!=
*/


#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;

bool isPrime(double number)
{
    for (double i = number - 1; i >= 2; i--) {
        if (fmod(number, i) == 0)
	    return false;
    }
    return true;
}
int main()
{
    double i = 42;
    int n = 0;
    while (n < 42)
    {
        if (isPrime(i))
        {
            n++;
	    cout.width(1); cout << left << "n = " << n;
            //Only for Text Alignment
            if (n < 10)
	    {
	        cout.width(40); cout << right << i << endl;
	    }
	    else
	    {
		cout.width(39); cout << right << i << endl;
	    }
            i += i - 1;
	}
	i++;
    }
    return 0;
}


(defun primep (n)                            ; https://stackoverflow.com/questions/15817350/
  (cond ((= 2 n) t)                          ; Hard-code "2 is a prime"
        ((= 3 n) t)                          ; Hard-code "3 is a prime"
        ((evenp n) nil)                      ; If we're looking at an even now, it's not a prime
        (t                                   ; If it is divisible by an odd number below its square root, it's not prime
	 (do* ((i 3 (incf i 2)))             ; Initialize to 3 and increment by 2 on every loop
	      ((or (> i (isqrt n))           ; Break condition index exceeds its square root
		   (zerop (mod n i)))        ; Break condition it is divisible
	       (not (zerop (mod n i))))))))  ; Returns not divisible, aka prime

(do ((i 42)                                  ; Initialize index to 42
     (c 0))                                  ; Initialize count of primes to 0
    ((= c 42))                               ; Break condition when there are 42 primes
  (incf i)                                   ; Increments index by unity
  (if (primep i)(progn (incf c)              ; If prime increment count of primes
		       (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


IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE lessThanTen
YOU SET US UP @NO PROBLEMO
STICK AROUND lessThanTen
TALK TO THE HAND n
GET TO THE CHOPPER lessThanTen
HERE IS MY INVITATION 10
LET OFF SOME STEAM BENNET n
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE lessThanTen
TALK TO THE HAND ", "
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET UP @NO PROBLEMO
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED


print join.with:", " map 1..10 => [to :string]


Loop, 9                ; loop 9 times
{
  output .= A_Index    ; append the index of the current loop to the output var
  If (A_Index <> 9)    ; if it isn't the 9th iteration of the loop
    output .= ", "     ; append ", " to the output var
}
MsgBox, %output%


#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.8.1
 Author:         Alexander Alvonellos

 Script Function:
	Output a comma separated list from 1 to 10, and on the tenth iteration of the
	output loop, only perform half of the loop.

#ce ----------------------------------------------------------------------------

Func doLoopIterative()
		Dim $list = ""
		For $i = 1 To 10 Step 1
			$list = $list & $i
			If($i = 10) Then ExitLoop
			$list = $list & ", "
		Next
		return $list & @CRLF
EndFunc

Func main()
	ConsoleWrite(doLoopIterative())
EndFunc

main()


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: i is 1024;
  begin
    while i > 0 do
      writeln(i);
      i := i div 2
    end while;
  end func;


put 1024 into x
log x
Repeat until x = 1
	divide x by 2
	log x
End repeat


n := 1024;
while n > 0 loop
    print( n );
    n := n div 2;
end loop;


var i = 1024
while (i > 0) {
    say i
    i //= 2
}


SetBatchLines, -1
iterations := 5
step := 10
iterations *= step
Loop,  % iterations
{
   If Mod(A_Index, step)
      Continue
   MsgBox, % A_Index
}
ExitApp


For each i from 0 to 100 by 7 do [Print: “i” ++ " is a multiple of 7!\n";];


M = [rand(1:20) for i in 1:5, j in 1:10]
R, C = size(M)

println("The full matrix is:")
println(M, "\n")

println("Find the first 20:")
for i in 1:R, j in 1:C
    n = M[i,j]
    @printf "%4d" n
    if n == 20
        println()
        break
    elseif j == C
        println()
    end
end


import java.util.Random

fun main(args: Array<String>) {
    val r = Random()
    val a = Array(10) { IntArray(10) { r.nextInt(20) + 1 } }
    println("array:")
    for (i in a.indices) println("row $i: " + a[i].asList())

    println("search:")
    Outer@ for (i in a.indices) {
        print("row $i: ")
        for (j in a[i].indices) {
            print(" " + a[i][j])
            if (a[i][j] == 20) break@Outer
        }
        println()
    }
    println()
}


program Increment_loop_index_within_loop_body;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function IsPrime(const a: UInt64): Boolean;
var
  d: UInt64;
begin
  if (a < 2) then
    exit(False);

  if (a mod 2) = 0 then
    exit(a = 2);

  if (a mod 3) = 0 then
    exit(a = 3);

  d := 5;

  while (d * d <= a) do
  begin
    if (a mod d = 0) then
      Exit(false);
    inc(d, 2);

    if (a mod d = 0) then
      Exit(false);
    inc(d, 4);
  end;

  Result := True;
end;

var
  i, n: UInt64;

begin
  FormatSettings.ThousandSeparator:= ',';
  i := 42;
  n := 0;
  while (n < 42) do
  begin
    if (isPrime(i)) then
    begin
      inc(n);
      Writeln('n = ', n: -20, ' ', floattostrF(i, ffNumber, 20,0):20);
      i := 2 * i - 1;
    end;
    inc(i);
  end;
  readln;
end.


func isPrime(number) {
    if number <= 1 {
        return false
    }
    else if number % 2 == 0 {
        return number == 2
    }

    var i = 3

    while (i * i) < number {
        if number % i == 0 {
            return false
        }
        i += 2
    }

    return true
}

var i = 42
var n = 0

while n < 42 {
    if isPrime(i) {
        n += 1
        print("n = \(n)\t\(i)")
        i += i - 1
    }
    i += 1
}


$ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf ", "};print}'


For(I,1,10)
 Disp I▶Dec
 If I=10
  Disp i
 Else
  Disp ","
 End
End


DIM i AS INTEGER

FOR i=1 TO 10
    PRINT i;
    IF i=10 THEN EXIT FOR
    PRINT ", ";
NEXT i


while (1) {
    print ++i
    if (i == 10) {
        print "\n"
        break
    }
    print ", "
}


begin
  integer i;
  i:=1024;
  while i>0 do
  begin
     outint(i,5);
     i:=i//2-1
  end
end


10 LET I=1024
20 IF I=0 THEN GOTO 60
30 PRINT I
40 LET I=INT (I/2)
50 GOTO 20


#n := 1024.
[n isPositive] whileTrue:
  [inform: number printString.
   n := n // 2]


[s atEnd] whileFalse: [s next. ...].
[foo notNil] whileTrue: [s next. ...].
[...] doWhile: [ ... someBooleanExpression ].
[...] doUntil: [ ... someBooleanExpression ].
[:exit | ... cold ifTrue:[exit value]. ...] loopWithExit


BEGIN {
  for (i= 2; i <= 8; i = i + 2) {
    print i
  }
  print "Ain't never too late!"
}


FOR I = 2 TO 8 STEP 2 : PRINT I; ", "; : NEXT I : PRINT "WHO DO WE APPRECIATE?"


1) the A.find function gets a value and a unidimensional array,
   then retuns the item matching the value else -1

{def A.find
 {def A.find.r
  {lambda {:val :arr :n :i :acc}
   {if {> :i :n}
    then -1
    else {if {= :val {A.get :i :arr}}
    then :i
    else {A.find.r :val :arr :n {+ :i 1} {A.addlast! :i :acc}}}}}}
 {lambda {:val :arr}
  {A.find.r :val :arr {- {A.length :arr} 1} 0 {A.new}}}}
-> A.find

{def A {A.new {S.serie 0 20}}}
-> A = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

{A.find 12 {A}}
-> 12             // the index
{A.find 21 {A}}
-> -1             // not found

2) the AA.find function gets a value and a bidimensional array,
   then returns the sequence of rows until the row containing the value,
   and diplays the row containing the value if it exists else displays "the value was not found".

{def AA.find
 {def AA.find.r
  {lambda {:val :arr :n :i}
   {if {> :i :n}
    then {br}:val was not found
    else {if {not {= {A.find :val {A.get :i :arr}} -1}}   // call the A.find function on each row
    then {br}:val was found in {A.get :i :arr}
    else {br}{A.get :i :arr} {AA.find.r :val :arr :n {+ :i 1}} }}}}
 {lambda {:val :arr}
  {AA.find.r :val :arr {- {A.length :arr} 1} 0}}}
-> AA.find

3) testing

3.1) the rn function returns a random integer between 0 and n
{def rn {lambda {:n} {round {* :n {random}}}}}
-> rn

3.2) creating a bidimensional array containing random integers between 0 and 20
{def AA {A.new {A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
               {A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
               {A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
               {A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}}}
-> AA = [[9,4,10,14,1],[4,12,7,18,13],[7,13,19,12,11],[18,4,2,14,15]]

3.3) calling with a value which can be in the array
{AA.find 12 {AA}}
->
[9,4,10,14,1]
12 was found in [4,12,7,18,13]

3.4) calling with a value outside of the array
{AA.find 21 {AA}}
->
[9,4,10,14,1]
[4,12,7,18,13]
[7,13,19,12,11]
[18,4,2,14,15]
21 was not found


// 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)
let cUL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:uint64)->n.ToString("N0",g))
// fN is primality by trial division
let fN g=pCache|>Seq.map uint64|>Seq.takeWhile(fun n->n*n<g)|>Seq.forall(fun n->g%n>0UL)
// unfold is sort of a loop incremented by 1 in this case
let fG n=Seq.unfold(fun n->Some(n,(n+1UL))) n|>Seq.find(fN)
// 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))


USING: formatting kernel math math.primes
tools.memory.private ;
IN: rosetta-code.loops-inc-body

42
0
[ dup 42 < ] [
    over prime? [
        1 + 2dup swap commas
        "n = %-2d  %19s\n" printf
        [ dup + 1 - ] dip
    ] when
    [ 1 + ] dip
] while
2drop


#include <stdio.h>

int main()
{
  int i;
  for (i = 1; i <= 10; i++) {
    printf("%d", i);
    printf(i == 10 ? "\n" : ", ");
  }
  return 0;
}


var i = 1024;
while i > 0 {
    print(i);
    i /= 2;
}


con
  _clkmode = xtal1 + pll16x
  _clkfreq = 80_000_000

obj
  ser : "FullDuplexSerial.spin"

pub main | n
  ser.start(31, 30, 0, 115200)

  n := 1024
  repeat while n > 0
    ser.dec(n)
    ser.tx(32)
    n /= 2

  waitcnt(_clkfreq + cnt)
  ser.stop
  cogstop(0)


--#SET TERMINATOR @

SET SERVEROUTPUT ON @

BEGIN
 DECLARE I SMALLINT DEFAULT 1024;

 Loop: WHILE (I > 0) DO
  CALL DBMS_OUTPUT.PUT_LINE(I);
  SET I = I / 2;
 END WHILE Loop;
END @


@echo off
for /l %%A in (1,2,10) do (
     echo %%A
)


local(a) = array(
    array(2, 12, 10, 4),
    array(18, 11, 9, 3),
    array(14, 15, 7, 17),
    array(6, 19, 8, 13),
    array(1, 20, 16, 5)
)

// Query expression
with i in delve(#a) do {
    stdoutnl(#i)
    #i == 20 ? return
}

// Nested loops
#a->foreach => {
    #1->foreach => {
        stdoutnl(#1)
        #1 == 20 ? return
    }
}


dim ar(10,10)
for i = 1 to 10
    for j = 1 to 10
        ar(i, j) = int(rnd(1) * 20) + 1
    next
next

flag=0
for x = 1 to 10
    for y = 1 to 10
        print ar(x,y)
        if ar(x,y) = 20 then
            flag=1
            exit for
        end if
    next
    if flag then exit for
next
print "Completed row ";x;" and column ";y


' version 18-01-2019
' compile with: fbc -s console

Function isprime(number As ULongInt) As UInteger

    If number Mod 2 = 0 Then Return 0
    If number Mod 3 = 0 Then Return 0
    Dim As UInteger i, max = Sqr(number)

    For i = 5 To max Step 2
        If number Mod i = 0 Then Return 0
    Next

    Return 1

End Function

' ------=< MAIN >=------

Dim As UInteger counter
Dim As ULongInt i

Print : Print
counter = 0
For i = 42 To &HFFFFFFFFFFFFFFFF    ' for next loop, loop maximum = 2^64-1
    If isprime(i) Then
        counter += 1
        Print Using "n =### ##################,"; counter; i
        If counter >= 42 Then Exit for
        i += i -1
    End If
Next

' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


package main

import(
    "golang.org/x/text/language"
    "golang.org/x/text/message"
)

func isPrime(n uint64) bool {
    if n % 2 == 0 {
        return n == 2
    }
    if n % 3 == 0 {
        return n == 3
    }
    d := uint64(5)
    for d * d <= n {
        if n % d == 0 {
            return false
        }
        d += 2
        if n % d == 0 {
            return false
        }
        d += 4
    }
    return true
}

const limit = 42

func main() {
    p := message.NewPrinter(language.English)
    for i, n := uint64(limit), 0; n < limit; i++ {
        if isPrime(i) {
            n++
            p.Printf("n = %-2d  %19d\n", n, i)
            i += i - 1
        }
    }
}


using System;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; ; i++)
        {
            Console.Write(i);
            if (i == 10) break;
            Console.Write(", ");
        }
        Console.WriteLine();
    }
}


#include <iostream>

int main()
{
  int i;
  for (i = 1; i<=10 ; i++){
    std::cout << i;
    if (i < 10)
     std::cout << ", ";
  }
  return 0;
}


for i in 1..10 do
        write(i, if i % 10 > 0 then ", " else "\n")


val n = ref 1024;
while !n > 0 do (
  print (Int.toString (!n) ^ "\n");
  n := !n div 2
)


local n=1024
while `n'>0 {
	display `n'
	local n=floor(`n'/2)
}


var i = 1024
while i > 0 {
  println(i)
  i /= 2
}


using System;

class Program {
    static void Main(string[] args) {
        for (int i = 2; i <= 8; i+= 2) {
            Console.Write("{0}, ", i);
        }

        Console.WriteLine("who do we appreciate?");
    }
}


for (int i = 1; i < 10; i += 2)
  std::cout << i << std::endl;


-- create two-dimensional array with random numbers
a = []
repeat with i = 1 to 20
  a[i] = []
  repeat with j = 1 to 20
    a[i][j] = random(20)
  end repeat
end repeat

-- iterate over rows and columns, print value, exit both loops if it's 20
repeat with i = 1 to 20
  repeat with j = 1 to 20
    v = a[i][j]
    put v
    if v=20 then exit repeat
  end repeat
  if v=20 then exit repeat
end repeat


Section Header

+ name := TEST_LOOP_NESTED;

- external := `#include <time.h>`;

Section Public

- main <- (
  + a : ARRAY2[INTEGER];
  + i, j: INTEGER;

  `srand(time(NULL))`;
  a := ARRAY2[INTEGER].create(0, 0) to (9, 9);
  0.to 9 do { ii : INTEGER;
    0.to 9 do { jj : INTEGER;
      a.put (`rand()`:INTEGER % 20 + 1) to (ii, jj);
    };
  };
  { i < 10 }.while_do {
    j := 0;
    { j < 10 }.while_do {
      ' '.print;
      a.item(i, j).print;
      (a.item(i, j) = 20).if {
        i := 999;
        j := 999;
      };
      j := j + 1;
    };
    i := i + 1;
    '\n'.print;
  };
  '\n'.print;
);


import Data.List
import Control.Monad (guard)

isPrime :: Int -> Bool
isPrime n
  | n <= 3 = n > 1
  | n `mod` 2 == 0 || n `mod` 3 == 0 = False
  | otherwise = l2 5 n
  where l2 d n = x > n || l3 d n
          where x = d * d
                l3 d n
                  | n `mod` d == 0       = False
                  | n `mod` (d + 2) == 0 = False
                  | otherwise = l2 (d + 6) n

showPrime :: Int -> Int -> [(Int, Int)]
showPrime i n = if isPrime i
                then (n, i) : showPrime (i+i) (n+1)
                else showPrime (i+1) n

digitGroup :: Int -> String
digitGroup = intercalate "," . reverse . map show . unfoldr (\n -> guard (n /= 0) >> pure (n `mod` 1000, n `div` 1000))

display :: (Int, Int) -> String
display (i, p) = show i ++ " " ++ digitGroup p

main = mapM_ (putStrLn . display) $ take 42 $ showPrime 42 1


using StringTools;
import haxe.Int64;

class PrimeNumberLoops {
  private static var limit = 42;

  static function isPrime(i:Int64):Bool {
    if (i == 2 || i == 3) {
      return true;
    } else if (i % 2 == 0 || i % 3 ==0) {
      return false;
    }
    var idx:haxe.Int64 = 5;
    while (idx * idx <= i) {
      if (i % idx == 0) return false;
      idx += 2;
      if (i % idx == 0) return false;
      idx += 4;
    }
    return true;
  }

  static function main() {
    var i:Int64 = 42;
    var n:Int64 = 0;
    while (n < limit) {
      if (isPrime(i)) {
        n++;
        Sys.println('n ${Int64.toStr(n).lpad(' ', 2)} ' +
                    '= ${Int64.toStr(i).lpad(' ', 19)}');
        i += i;
        continue;
      }
      i++;
    }
  }
}


; Functional version
(apply str (interpose ", " (range 1 11)))

; Imperative version
(loop [n 1]
   (printf "%d" n)
   (if (< n 10)
       (do
	(print ", ")
	(recur (inc n)))))


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Loop-N-And-Half.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  I    PIC 99.
       01  List PIC X(45).

       PROCEDURE DIVISION.
           PERFORM FOREVER
               *> The list to display must be built up because using
               *> DISPLAY adds an endline at the end automatically.
               STRING FUNCTION TRIM(List) " "  I  INTO List

               IF I = 10
                   EXIT PERFORM
               END-IF

               STRING FUNCTION TRIM(List) "," INTO List

               ADD 1 TO I
           END-PERFORM

           DISPLAY List

           GOBACK
           .


# Loop plus half.  This code shows how to break out of a loop early
# on the last iteration.  For the contrived example, there are better
# ways to generate a comma-separated list, of course.
start = 1
end = 10
s = ''
for i in [start..end]
  # the top half of the loop executes every time
  s += i
  break if i == end
  # the bottom half of the loop is skipped for the last value
  s += ', '
console.log s


set i 1024
while {$i > 0} {
    puts $i
    set i [expr {$i / 2}]
}


\newcount\rosetta
\rosetta=1024
\loop
    \the\rosetta\endgraf
    \divide\rosetta by 2
    \ifnum\rosetta > 0
\repeat
\end


shared void run() {

	for(i in (2..8).by(2)) {
		process.write("``i`` ");
	}
	print("who do we appreciate?");
}


// Can be set on commandline via --N=x
config const N = 3;

for i in 1 .. 10 by N {
  writeln(i);
}


repeat with i = 1 to 10
    repeat with j = 1 to 10
        put random(20) into aNums[i,j]
    end repeat
end repeat

repeat with i = 1 to 10
    repeat with j = 1 to 10
        if aNums[i,j] = 20 then
            put true into exitLoop
            exit repeat
        end if
    end repeat
    if exitLoop then exit repeat
end repeat

if exitLoop then
    put "20 found in" && i & comma & j
else
    put "20 not found"
end if


make "a mdarray [10 10]

for [j 1 10] [for [i 1 10] [mdsetitem list :i :j :a (1 + random 20)]]

to until.20
  for [j 1 10] [
    for [i 1 10] [
      type mditem list :i :j :a
      type "| |
      if equal? 20 mditem list :i :j :a [stop]
    ]
    print "||
  ]
end
until.20


public class LoopIncrementWithinBody {

    static final int LIMIT = 42;

    static boolean isPrime(long n) {
        if (n % 2 == 0) return n == 2;
        if (n % 3 == 0) return n == 3;
        long d = 5;
        while (d * d <= n) {
            if (n % d == 0) return false;
            d += 2;
            if (n % d == 0) return false;
            d += 4;
        }
        return true;
    }

    public static void main(String[] args) {
        long i;
        int n;
        for (i = LIMIT, n = 0; n < LIMIT; i++)
            if (isPrime(i)) {
                n++;
                System.out.printf("n = %-2d  %,19d\n", n, i);
                i += i - 1;
            }
    }
}


{i:42, count:0}
| while( .count <= 42;
    .emit = null
    | .i += 1
    | if .i|is_prime
      then
      .count += 1
      | .emit = "count at \(.i) is \(.count)"
      | .i = .i + .i - 1
      else .
      end )
| select(.emit).emit


<cfloop index = "i" from = "1" to = "10">
  #i#
  <cfif i EQ 10>
    <cfbreak />
  </cfif>
  ,
</cfloop>


(loop for i from 1 below 10 do
        (princ i) (princ ", ")
        finally (princ i))


include "cowgol.coh";

var i: uint8 := 1;
loop
    print_i8(i);
    if i == 10 then break; end if;
    print(", ");
    i := i + 1;
end loop;
print_nl();


import std.stdio;

void main() {
    for (int i = 1; ; i++) {
        write(i);
        if (i >= 10)
            break;
        write(", ");
    }

    writeln();
}


Local i
1024 → i
While i > 0
  Disp i
  intDiv(i, 2) → i
EndWhile


%num = 1024;
while(%num > 0)
{
    echo(%num);
    %num = mFloor(%num / 2);
}


DECLARE @i INT = 1024;
WHILE @i >0
BEGIN
    PRINT @i;
    SET @i = @i / 2;
END;


1024 [dup print 2 / floor] [dup 0 >] while drop


(loop [i 0]
  (println i)
  (when (< i 10)
    (recur (+ 2 i))))

(doseq [i (range 0 12 2)]
  (println i))


% This prints all odd digits

start_up = proc ()
    po: stream := stream$primary_output()

    for i: int in int$from_to_by(1, 10, 2) do
        stream$putl(po, int$unparse(i))
    end
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Display-Odd-Nums.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  I PIC 99.

       PROCEDURE DIVISION.
           PERFORM VARYING I FROM 1 BY 2 UNTIL 10 < I
               DISPLAY I
           END-PERFORM

           GOBACK
           .


t = {}
for i = 1, 20 do
  t[i] = {}
  for j = 1, 20 do t[i][j] = math.random(20) end
end
function exitable()
  for i = 1, 20 do
    for j = 1, 20 do
      if t[i][j] == 20 then
        return i, j
      end
    end
  end
end
print(exitable())


Module Checkit {
            Dim A(10,10)<<Random(1, 20)
            For k=1 to 2 {
                  For i=0 to 9 {
                        For j=0 to 9 {
                              Print A(i,j)
                              if A(i,j)=20 then goto there
                        }
                  }
                  there:
                  Print "...ok", k
            }
}
Checkit


using Primes, Formatting

function doublemyindex(n=42)
    shown = 0
    i = BigInt(n)
    while shown < n
        if isprime(i + 1)
            shown += 1
            println("The index is ", format(shown, commas=true), " and ",
                                     format(i + 1, commas=true), " is prime.")
            i += i
        end
        i += 1
    end
end

doublemyindex()


// version 1.2.60

fun isPrime(n: Long): Boolean {
    if (n % 2L == 0L) return n == 2L
    if (n % 3L == 0L) return n == 3L
    var d = 5L
    while (d * d <= n) {
        if (n % d == 0L) return false
        d += 2L
        if (n % d == 0L) return false
        d += 4L
    }
    return true
}

fun main(args: Array<String>) {
    var i = 42L
    var n = 0
    do {
        if (isPrime(i)) {
            n++
            System.out.printf("n = %-2d  %,19d\n", n, i)
            i += i - 1
        }
        i++
    }
    while (n < 42)
}


#!/bin/ksh

# Increment loop index within loop body

#	# Variables:
#
integer INDX_START=42 N_PRIMES=42

#	# Functions:
#

#	# Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
	typeset _n ; integer _n=$1
	typeset _i ; integer _i

	(( _n < 2 )) && return 0
	for (( _i=2 ; _i*_i<=_n ; _i++ )); do
		(( ! ( _n % _i ) )) && return 0
	done
	return 1
}

 ######
# main #
 ######
integer i n=0
for ((i=INDX_START; n<N_PRIMES; i++)); do
	_isprime ${i}
	if (( $? )); then
		printf "%,18d is prime, %2d primes found(so far)\n" ${i} $((++n))
		(( i+=$i ))
	fi
done


-- Returns boolean indicate whether x is prime
function isPrime (x)
  if x < 2 then return false end
  if x < 4 then return true end
  if x % 2 == 0 then return false end
  for d = 3, math.sqrt(x), 2 do
    if x % d == 0 then return false end
  end
  return true
end

-- Main procedure
local n, i = 0, 42
while n < 42 do
  if isPrime(i) then
    n = n + 1
    print("n = " .. n, i)
    i = 2 * i - 1
  end
  i = i + 1
end


String loopPlusHalf(start, end) {
  var result = '';
  for(int i = start; i <= end; i++) {
    result += '$i';
    if(i == end) {
      break;
    }
    result += ', ';
  }
  return result;
}

void main() {
  print(loopPlusHalf(1, 10));
}


program LoopsNPlusOneHalf;

{$APPTYPE CONSOLE}

var
  i: integer;
const
  MAXVAL = 10;
begin
  for i := 1 to MAXVAL do
  begin
    Write(i);
    if i < MAXVAL then
      Write(', ');
  end;
  Writeln;
end.


proc nonrec main() void:
    byte i;
    i := 1;
    while
        write(i);
        i := i + 1;
        i <= 10
    do
        write(", ")
    od
corp


var i : Integer;

for i := 1 to 10 do begin
   Print(i);
   if i < 10 then
      Print(', ');
end;


$$ MODE TUSCRIPT
i=1024
LOOP
   PRINT i
   i=i/2
   IF (i==0) EXIT
ENDLOOP


variables
	numeric I
endvariables

I = 1024
while (I > 0)
	putmess I
	I = (I/2)[trunc]
endwhile


<cfloop from="0" to="99" step="3" index="i">
  <Cfoutput>#i#</Cfoutput>
</cfloop>


(format t "~{~S, ~}who do we appreciate?~%" (loop for i from 2 to 8 by 2 collect i))


import std.stdio, std.range;

void main() {
    // Print odd numbers up to 9.
    for (int i = 1; i < 10; i += 2)
        writeln(i);

    // Alternative way.
    foreach (i; iota(1, 10, 2))
        writeln(i);
}


(m,n) := LinearAlgebra:-Dimensions(M):
for i from 1 to m do
  for j from 1 to n do
    print(M[i,j]);
    if M[i,j] = 20 then
      (i,j):=m,n; next;
    end if;
  end do;
end do:


INFINITE CSECT ,                       this PGM control section
INFINITE AMODE 31                      addressing mode 31 bit
INFINITE RMODE ANY                     loader can load either 24 or 31
         BAKR  14,0                    stack caller's register contents
         LR    12,15                   establish base
         LA    13,0                    no savearea
         USING INFINITE,12             base to assembler
         LA    10,1                    1 in reg 10
         LA    11,2                    2 in reg 11
LOOP     EQU   *
         CR    10,11                   1==2?
         BE    RETURN                  Yes, exit.
        WTO    'SPAM',ROUTCDE=11       print SPAM to syslog
         B     LOOP                    No, check again.
RETURN   PR    ,                       return to caller
         END   INFINITE


InfiniteLoop	LDX #0
PrintLoop:	LDA MSG,x
		JSR PrintAccumulator	;routine not implemented
		INX
		CPX #5
		BNE PrintLoop
		BEQ InfiniteLoop

MSG		.byte "SPAM", $0A


        .cr  6800
        .tf  spam6800.obj,AP1
        .lf  spam6800
;=====================================================;
;       Infinite SPAM loop for the Motorola 6800      ;
;                 by barrym 2013-04-10                ;
;-----------------------------------------------------;
; Prints the message "SPAM" repeatedly to an ascii    ;
;   terminal (console) connected to a 1970s vintage   ;
;   SWTPC 6800 system, which is the target device for ;
;   this assembly.                                    ;
; Many thanks to:                                     ;
;   swtpc.com for hosting Michael Holley's documents! ;
;   sbprojects.com for a very nice assembler!         ;
;   swtpcemu.com for a very capable emulator!         ;
; reg x is the string pointer                         ;
; reg a holds the ascii char to be output             ;
;-----------------------------------------------------;
outeee   =   $e1d1      ;ROM: console putchar routine
        .or  $0f00
;-----------------------------------------------------;
main    ldx  #string    ;Point to the string
        bra  puts       ;  and print it
outs    jsr  outeee     ;Emit a as ascii
        inx             ;Advance the string pointer
puts    ldaa ,x         ;Load a string character
        bne  outs       ;Print it if non-null
        bra  main       ;else restart
;=====================================================;
string  .as  "SPAM",#13,#10,#0
        .en


Module CheckIt {
      Function IsPrime (x) {
            if x<=5 OR frac(x) then {
                  if x = 2 OR x = 3 OR x = 5 then =true
                  Break
            }
            if x mod 2 else exit
            if x mod 3 else exit
            x1=sqrt(x): [email protected]
            {if x mod d else exit
                  d += [email protected]: if d>x1 then =true : exit
                  if x mod d else exit
                  d += [email protected]: if d<= x1 else =true: exit
                  loop
             }
      }
      \\ For Next loops or For {} loops can't change iterator variable (variable has a copy of real iterator)
      \\ In those loops we have to use Continue to skip lines and repeat the loop.
      \\ so we have to use Block iterator, using Loop which set a flag current block to repeat itself once.
      def long Limit=42, n
      def decimal i
      i=Limit
      {
            if n<Limit Else exit
            if isPrime(i)  then n++ : Print format$("n={0::2}: {1:-20}", n, str$(i,"#,###")) : i+=i-1
            i++
            loop
      }
}
CheckIt


i := 42:
count := 0:
while(count < 42) do
	i := i+1:
	if type(i,prime) then
		count := count + 1:
		printf("n=%-2d     %19d\n", count,i):
		i := 2*i -1:
	end if:
end do:


'Loops Increment loop index within loop body - 16/07/2018
imax=42
i=0
n=42
While i<imax
  isprime_n()
  If ret_isprime_n Then
    i=i+1
    format_i()
    format_n()
    TextWindow.WriteLine("i="+ret_format_i+" : "+ret_format_n)
    n=n+n-1
  EndIf
  n=n+1
EndWhile

Sub isprime_n
  If n=2 Or n=3 Then
    ret_isprime_n="True"
  ElseIf Math.Remainder(n,2)=0 Or Math.Remainder(n,3)=0 Then
    ret_isprime_n="False"
  Else
    j=5
    While j*j<=n
      If Math.Remainder(n,j)=0 Or Math.Remainder(n,j+2)=0 Then
        ret_isprime_n="False"
        Goto exitsub
      EndIf
      j=j+6
    EndWhile
    ret_isprime_n="True"
  EndIf
exitsub:
EndSub 'isprime_n

Sub format_i
  ret_format_i=Text.GetSubText("   ",1,3-Text.GetLength(i))+i
EndSub 'format_i

Sub format_n
  nn=""
  l=-1
  For k=Text.GetLength(n) To 1 Step -1
    l=l+1
    cc=Text.GetSubText(n,k,1)
    If l=3 Then
      cv=","
      l=0
    Else
      cv=""
    EndIf
    nn=Text.Append(cc,Text.Append(cv,nn))
  EndFor
  space="                    "
  nn=Text.GetSubText(space,1,Text.GetLength(space)-Text.GetLength(nn))+nn
  ret_format_n=nn
EndSub 'format_n


limit = 42

def isPrime(n)
    if ((n % 2) = 0) or ((n % 3) = 0)
        return false
    end
    d = 5
    while (d * d) <= n
        if (n % d) = 0
            return false
        end
        d += 2
        if (n % d) = 0
            return false
        end
        d += 4
    end
    return true
end

i = limit
for (n = 0) (n < limit) (i += 1)
    if isPrime(i)
        n += 1
        print format("n = %-2d  %,19d\n", n, i)
        i += i - 1
    end
end


var i := 1
while (true) {
    print(i)
    if (i >= 10) { break }
    print(", ")
    i += 1
}


[ N and a half times loop
  =======================

  A program for the EDSAC

  Works with Initial Orders 2 ]

        T56K
        GK

        [email protected]
[  1 ]  [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]

        [email protected]
        [email protected]
        [email protected]
        [email protected]

[ 11 ]  [email protected]
        [email protected]
        [email protected]
        [email protected]
        ZF

[ 16 ]  #F
[ 17 ]  PF
[ 18 ]  QF
[ 19 ]  NF
[ 20 ]  !F
[ 21 ]  @F
[ 22 ]  &F
[ 23 ]  JF
[ 24 ]  PF
[ 25 ]  PF

        EZPF


(echo 1024>p.res;tail -f p.res) | while read a ; do
   test $a -gt 0 && (expr $a / 2  >> p.res ; echo $a) || exit 0
done


decl int n
set n 1024

while (> n 0)
    out n endl console
    set n (int (/ n 2))
end while


#import nat

g = ~&h-> ^C/[email protected] ~&

#show+

main = %nP*=tx g <1024>


1024 [0 >] [
   dup puts
   2 / >int
] while


# first value: 1
# max value: 9
# step: 2
for( i = 1 : 2 : 9 ) io.writeln( i )


program LoopWithStep;

{$APPTYPE CONSOLE}

var
  i: Integer;
begin
  i:=2;
  while i <= 8 do begin
    WriteLn(i);
    Inc(i, 2);
  end;
end.


for(i = 2, i <= 8,i += 2){
   show ", " + i
}
showln "who do we appreciate?"


var i : Integer;

for i := 2 to 8 step 2 do
   PrintLn(i);


data: apply(matrix, makelist(makelist(random(100), 20), 20))$

find_value(a, x) := block(
   [p, q],
   [p, q]: matrix_size(a),
   catch(
      for i thru p do
         for j thru q do
            if a[i, j] = x then throw([i, j]),
      'not\ found
   )
)$

find_value(data, 100);
not found


fn scan_Nested arr =
(
	for subArray in arr where classof subArray == Array do
	(
		for item in subArray do
		(
			print item as string
			if item == 20 do return OK
		)
	)
)


doSPAM:
LEA Message,A0
JSR PrintString
JMP doSPAM

Message:
DC.B "SPAM",13,10,0
EVEN


Spam:
mov ah,02h
mov dl,'S'  ;VASM replaces a character in single quotes with its ascii equivalent
int 21h     ;Print Char routine

mov dl,'P'
int 21h

mov dl, 'A'
int 21h

mov dl, 'M'
int 21h

mov dl,13  ;Carriage Return
int 21h

mov dl,10  ;New Line
int 21h

jmp Spam


#! /usr/local/bin/newlisp

(define (prime? n)
 (and
   (set 'lst (factor n))
   (= (length lst) 1)))

(define (thousands_separator i)
    (setq i (string i))
    (setq len (length i))
    (setq i (reverse (explode i)))
    (setq o "")
    (setq count3 0)
    (dolist (x i)
        (setq o (string o x))
        (inc count3)
        (if (and (= 3 count3) (< (+ $idx 1) len))
            (begin
            (setq o (string o "_"))
            (setq count3 0))))

    (reverse o))

;- - - Main begins here
(setq i 42)
(setq n 0)
(while (< n 42)
    (if (prime? i)
        (begin
            (inc n)
            (println (string "n = " n " -> " (thousands_separator i)))
            (setq i (+ i i -1))))
    (inc i)
)

(exit)


import strformat
from strutils import insertSep

func isPrime(i: int): bool =
  if i == 2 or i == 3: return true
  elif i mod 2 == 0 or i mod 3 == 0: return false
  var idx = 5
  while idx*idx <= i:
    if i mod idx == 0: return false
    idx.inc 2
    if i mod idx == 0: return false
    idx.inc 4
  result = true

const limit = 42
proc main =
  var
    i = 42
    n = 0
  while n < limit:
    if i.isPrime:
      inc n
      echo &"""n {n:>2} = {($i).insertSep(sep=','):>19}"""
      i.inc i
      continue
    inc i

main()


defmodule Loops do
  def n_plus_one_half([]), do: IO.puts ""
  def n_plus_one_half([x]), do: IO.puts x
  def n_plus_one_half([h|t]) do
    IO.write "#{h}, "
    n_plus_one_half(t)
  end
end

Enum.to_list(1..10) |> Loops.n_plus_one_half


%% Implemented by Arjun Sunel
-module(loop).
-export([main/0]).

main() ->
	for_loop(1).

 for_loop(N) ->
 	if N < 10 ->
		io:format("~p, ",[N] ),
		for_loop(N+1);
	true ->
		io:format("~p\n",[N])
	end.


FOR I=1 TO 10 DO
    PRINT(I;)
    EXIT IF I=10
    PRINT(", ";)
END FOR


for i = 1 to 10 do
    printf(1, "%g", {i})
    if i < 10 then
        puts(1, ", ")
    end if
end for


int i = 1024;
while (i > 0) {
  stdout.printf("%d\n", i);
  i /= 2;
}


Public Sub LoopsWhile()
    Dim value As Integer
    value = 1024
    Do While value > 0
        Debug.Print value
        value = value / 2
    Loop
End Sub


//  Basic @LOOP while: verb

@LOOP init:{@VAR n = 1024} while:(n > 0) next:{n /= 2}
{
     @SAY n;
};


//Prints odd numbers from 1 to 10
for i in 1^2..10 {
    print(i)
}


var i := 2
while (i <= 8) {
    print(`$i, `)
    i += 2
}
println("who do we appreciate?")


For row = 0 To 10
  For col = 0 To 10
    array[row][col] = Math.GetRandomNumber(20)
  EndFor
EndFor
For row = 0 To 10
  For col = 0 To 10
    TextWindow.WriteLine("row "+row+" col "+col+" value "+array[row][col])
    If array[row][col] = 20 Then
      Goto exit_for_row
    EndIf
  EndFor
EndFor
exit_for_row:


a = make(10, make(10));
for i in [1..10]
  for j in [1..10]
    a[i][j] = random(20);
  endfor
endfor
for i in [1..10]
  s = "";
  for j in [1..10]
    s += tostr(" ", a[i][j]);
    if (a[i][j] == 20)
      break i;
    endif
  endfor
  player:tell(s);
  s = "";
endfor
player:tell(s);


(defun spam ()
   (declare (xargs :mode :program))
   (if nil
       nil
       (prog2$ (cw "SPAM~%")
               (spam))))


PROC Main()
  DO
    PrintE("SPAM")
  OD
RETURN


use ntheory qw(is_prime);

$i = 42;
while ($n < 42) {
    if (is_prime($i)) {
        $n++;
        printf "%2d %21s\n", $n, commatize($i);
        $i += $i - 1;
    }
    $i++;
}

sub commatize {
    (my $s = reverse shift) =~ s/(.{3})/$1,/g;
    $s =~ s/,$//;
    $s = reverse $s;
}


atom i=42, n=1
while n<=42 do
    if is_prime(i) then
        printf(1,"n = %-2d  %,19d\n", {n, i})
        n += 1
        i += i-1
    end if
    i += 1
end while


def isPrime(n):
    for x in 2, 3:
        if not n % x:
            return n == x
    d = 5
    while d * d <= n:
        for x in 2, 4:
            if not n % d:
                return False
            d += x
    return True

i = 42
n = 0
while n < 42:
    if isPrime(i):
        n += 1
        print('n = {:2} {:20,}'.format(n, i))
        i += i - 1
    i += 1


let rec print (lst : int list) =
    match lst with
    | hd :: [] ->
        printf "%i " hd
    | hd :: tl ->
        printf "%i, " hd
        print tl
    | [] -> printf "\n"

print [1..10]


: print-comma-list ( n -- )
    [ [1,b] ] keep '[
        [ number>string write ]
        [ _ = [ ", " write ] unless ] bi
    ] each nl ;


for value = 1 to 10
    formiddle
        >> value
        >> ", "
    end
    forlast: > value
end


module main;
  integer i;

  initial begin
      i = 1024;

      while( i > 0) begin
        $display(i);
        i = i / 2;
      end
      $finish ;
    end
endmodule


let i = 1024
while i > 0
    echo i
    let i = i / 2
endwhile


Dim x = 1024
Do
    Console.WriteLine(x)
    x = x \ 2
Loop While x > 0


fn main() {
    mut i := 1024
    for i > 0 {
        println(i)
        i /= 2
    }
}


open monad io

for m s n | n > m = do return ()
          | else = do
              putStrLn (show n)
              for m s (n+s)

_  = for 10 2 0 ::: IO


public program()
{
    for(int i := 2, i <= 8, i += 2  )
    {
        console.writeLine:i
    }
}


defmodule Loops do
  def for_step(n, step) do
    IO.inspect Enum.take_every(1..n, step)
  end
end

Loops.for_step(20, 3)


%% Implemented by Arjun Sunel
%% for_loop/4 by Bengt Kleberg.
-module(loop_step).
-export([main/0, for_loop/1, for_loop/4]).

 % This Erlang code for "For Loop" is equivalent to: " for (i=start;  i<end ; i=i+2){ printf("* ");} " in C language.

main() ->
	for_loop(1).

 for_loop( N ) ->
	for_loop( N, 4, 2, fun() -> io:fwrite("* ") end ).

for_loop( I, End, Step, Do ) when N < End ->
    Do(),
    for_loop( I+Step, End, Step, Do );
for_loop( _I, _End, _Step, _Do ) -> ok.


NESTLOOP
 ;.../loops/nested
 ;set up the 2D array with random values
 NEW A,I,J,K,FLAG,TRIGGER
 SET K=15 ;Magic - just to give us a size to work with
 SET TRIGGER=20 ;Magic - the max value, and the end value
 FOR I=1:1:K FOR J=1:1:K SET A(I,J)=$RANDOM(TRIGGER)+1
 ;Now, search through the array, halting when the value of TRIGGER is found
 SET FLAG=0
 SET (I,J)=0
 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


/**
 Loops/Nested in Neko
 Tectonics:
   nekoc loops-nested.neko
   neko loops-nested.neko
*/

var random = $loader.loadprim("[email protected]_new", 0)();
var random_int = $loader.loadprim("[email protected]_int", 2);

var values = $amake(10);
var row = 0;
var col = 0;

while row < 10 {
  values[row] = $amake(10);
  col = 0;
  while col < 10 {
    values[row][col] = random_int(random, 20) + 1;
    col += 1;
  }
  row += 1;
}

/* Look for a 20 */
/*
 To break out of nested loops, (without using labels and $goto),
   Neko needs the value of the inner loop(s).
 The break statement sets the return value of a loop expression.
 Without a break, the value of a loop expression is unspecified.
*/
var inner;
row = 0;
while row < 10 {
  col = 0;
  inner = while col < 10 {
    $print("values[", row, "][", col, "] = ", values[row][col], "\n");
    if values[row][col] == 20 break true;
    col += 1;
  }
  if $istrue(inner) break;
  row += 1;
}


i <- 42
primeCount <- 0
while(primeCount < 42)
{
  if(gmp::isprime(i) == 2)#1 means "probably prime" and won't come up for numbers this small, 2 is what we want.
  {
    primeCount <- primeCount + 1
    extraCredit <- format(i, big.mark=",", scientific = FALSE)
    cat("Prime count:", paste0(primeCount, ";"), "The prime just found was:", extraCredit, "\n")
    i <- i + i#This is missing the -1 from the Kotlin solution. There is no need to check i + i (it's even).
  }
  i <- i + 1
}


#lang racket

(require math/number-theory)

(define (comma x)
  (string-join
   (reverse
    (for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
      (cond
        [(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
        [else (string digit)])))
   ""))

(let loop ([x 42] [cnt 0])
  (cond
    [(= cnt 42) (void)]
    [(prime? x) (printf "~a: ~a\n" (add1 cnt) (comma x))
                (loop (* 2 x) (add1 cnt))]
    [else (loop (add1 x) cnt)]))


# 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;


class Main
{
  public static Void main ()
  {
    for (Int i := 1; i <= 10; i++)
    {
      Env.cur.out.writeObj (i)
      if (i == 10) break
      Env.cur.out.writeChars (", ")
    }
    Env.cur.out.printLine ("")
  }
}


#APPTYPE CONSOLE
FOR DIM i = 1 TO 10
    PRINT i;
    IF i < 10 THEN PRINT ", ";
NEXT
PAUSE


: comma-list ( n -- )
  dup 1 ?do  i 1 .r ." , " loop
  . ;


C     Loops N plus one half - Fortran IV (1964)
      INTEGER I
      WRITE(6,301) (I,I=1,10)
  301 FORMAT((I3,','))
      END


i <- 1024
while (i > 0)
  prn i
  i <- (int i/2)


let number=1024
while number>0.5
print 1 number
let number=number/2
wend
end


var i = 1024
while (i > 0) {
    System.print(i)
    i = (i / 2).floor
}


      FOR N=2 TO 8 STEP 1.5 DO
        PRINT(N)
      END FOR


for i in 2..2..8 do
   printf "%d, " i
printfn "done"


using System;
using System.Console;
using Nemerle.Imperative;

module NestedLoops
{
    Main() : void
    {
        def arr = array(10, 10);
        def rnd = Random();

        foreach ((i, j) in $[(i, j) | i in [0 .. 9], j in [0 .. 9]])
            arr[i, j] = rnd.Next(1, 21);

        Finish:
        {
            foreach ((i, j) in $[(i, j) | i in [0 .. 9], j in [0 .. 9]])
            {
                Write("{0}  ", arr[i, j]);
                when (arr[i, j] == 20) Finish();
            }
        }
    }
}


/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

  say
  say 'Loops/Nested'

  rnd = Random()
  dim2 = int[10, 10]

  -- build sample data
  loop i1 = 0 for dim2.length
    loop i2 = 0 for dim2[i1].length
      dim2[i1, i2] = rnd.nextInt(20) + 1
      end i2
    end i1

  -- run test
  loop x1 = 0 for dim2.length
    say Rexx(x1 + 1).right(4)': \-'
    loop x2 = 0 for dim2[x1].length
      say Rexx(dim2[x1, x2]).right(3) || '\-'
      if dim2[x1, x2] = 20 then leave x1
      finally
        say
      end x2
    finally
      say
    end x1


 begin
   integer i;
   for i:=1 step 0 until 2 do
     outtext("spam")
 end


/*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*/
if limit=='' | limit==","  then limit=42         /*Not specified?  Then use the default.*/
n=0                                              /*the count of number of primes found. */
     do z=42  until n==limit                     /* ◄──this DO loop's index is modified.*/
     if isPrime(z)  then do;  n=n + 1            /*Z  a prime?  Them bump prime counter.*/
                              say right('n='n, 9)     right(commas(z), d)
                              z=z + z - 1        /*also, bump the  DO  loop index  Z.   */
                         end
     end   /*z*/                                 /* [↑] a small tribute to Douglas Adams*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas:  parse arg _;  do j=length(_)-3  to 1  by -3; _=insert(',', _, j); end;   return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure; parse arg #;         if wordpos(#, '2 3 5 7')\==0  then return 1
                                         if # // 2==0 | # // 3    ==0  then return 0
           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. */


# Project : Loops/Increment loop index within loop body

load "stdlib.ring"
i = 42
n = 0
while n < 42
         if isprime(i)
            n = n + 1
            see "n = " + n + "    " + i + nl
            i = i + i - 1
         ok
         i = i + 1
end


require 'prime'

limit = 42
i = 42
n = 0

while n < limit do
  if i.prime? then
    n += 1
    puts "n = #{n}".ljust(7) + ":" + "#{i.to_s.reverse.scan(/\d{3}|.+/).join(",").reverse}".rjust(19)
    i += i
  else
    i += 1
  end
end


' FB 1.05.0 Win64

For i As Integer = 1 To 10
  Print Str(i);
  If i < 10 Then Print ", ";
Next

Print
Sleep


window 1

long i, num = 10

for i = 1 to num
  print i;
  if i = num then break
  print @", ";
next i

HandleEvents


Public Sub Main()
Dim siLoop As Short

For siLoop = 1 To 10
  Print siLoop;
  If siLoop <> 10 Then Print ", ";
Next

End


n := 10;
for i in [1 .. n] do
    Print(i);
    if i < n then
        Print(", ");
    else
        Print("\n");
    fi;
od;


; NASM 64 bit X86-64 assembly on Linux

global main
extern printf

segment .data

printffmt db `%ld\n`,0

segment .text

main:
    push rbp
    mov rbp,rsp

; used rbx and r12 because printf preserves these values

    mov rbx,1024                 ; start with 1024
    mov r12,2                    ; load 2 as divisor

.toploop                         ; top of while loop
    cmp rbx,0                    ; compare to 0
    jle .done                    ; exit 0 or less

    lea rdi,[printffmt]          ; print number in rsi
    mov rsi,rbx                  ; mov to rsi as argument
    call printf

; calculate n/2 and save
    xor rdx,rdx                  ; clear rdx for division
    mov rax,rbx                  ; mov number to rax for division
    idiv r12                     ; divide by 2
    mov rbx,rax                  ; save n/2

    jmp .toploop                 ; next loop

.done
    xor rax,rax                  ; return code 0
    leave                        ; fix stack
    ret                          ; return


i% = 1024
DO WHILE i% > 0
  PRINT i%
  i% = i% / 2
LOOP


class Main
{
  public static Void main ()
  {
    Int step := 5
    for (Int i := 0; i < 100; i += step)
    {
      echo (i)
    }
  }
}


#APPTYPE CONSOLE

DIM n AS INTEGER
FOR n = 2 TO 8 STEP 2
    PRINT n;
    IF n < 8 THEN PRINT " ";
NEXT
PRINT ", who will we obliterate?"
PAUSE


(let (a (array 10 10))
  (dotimes (i 10)
    (dotimes (j 10)
      (setf (a i j) (rand 21))))
  (catch
      (dotimes (i 10)
	(dotimes (j 10)
	  (print (a i j))
	  (print " ")
	  (if (= 20 (a i j))
	      (throw))))))


import random, strutils

const ArrSize = 10

var a: array[ArrSize, array[ArrSize, int]]
var s = ""

randomize()   # Different results each time this runs.

# Initialize using loops on items rather than indexes.
for row in a.mitems:
  for item in row.mitems:
    item = rand(1..20)

block outer:
  # Loop using indexes.
  for i in 0..<ArrSize:
    for j in 0..<ArrSize:
      if a[i][j] < 10: s.add(' ')
      addf(s, "$#", $a[i][j])
      if a[i][j] == 20: break outer
      s.add(", ")
    s.add('\n')

echo s


begin
    for i := 1 step 0 until 2 do write( "SPAM" )
end.


PROC main()
  LOOP
    WriteF('SPAM')
  ENDLOOP
ENDPROC


.global main

main:

loop:
    ldr r0, =message
    bl printf
    b loop

message:
    .asciz "SPAM\n"


import scala.annotation.tailrec

object LoopIncrementWithinBody extends App {
  private val (limit, offset) = (42L, 1)

  @tailrec
  private def loop(i: Long, n: Int): Unit = {

    def isPrime(n: Long) =
      n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) &&
        ((5 to math.sqrt(n).toInt by 2).par forall (n % _ != 0))

    if (n < limit + offset)
      if (isPrime(i)) {
        printf("n = %-2d  %,19d%n".formatLocal(java.util.Locale.GERMANY, n, i))
        loop(i + i + 1, n + 1)
      } else loop(i + 1, n)
  }

  loop(limit, offset)
}


$ include "seed7_05.s7i";

const func boolean: isPrime (in integer: number) is func
  result
    var boolean: result is FALSE;
  local
    var integer: count is 2;
  begin
    if number = 2 then
      result := TRUE;
    elsif number > 2 then
      while number rem count <> 0 and count * count <= number do
        incr(count);
      end while;
      result := number rem count <> 0;
    end if;
  end func;

const proc: main is func
  local
    var integer: i is 42;
    var integer: n is 0;
  begin
    for i range 42 to integer.last until n >= 42 do
      if isPrime(i) then
        incr(n);
        writeln("n = " <& n lpad 2 <& i lpad 16);
        i +:= i - 1;
      end if;
    end for;
  end func;


numFound := 0.
idx := 42.
[:exit |
    idx := idx + 1.
    idx isPrime ifTrue:[
        numFound := numFound + 1.
        '%d %20d\n' printf:{numFound . idx} on:Transcript.
        idx := idx + idx - 1.
        numFound == 42 ifTrue:exit
    ].
] loopWithExit.


str = ""
for(i = 1; i <= 10; i += 1)
    {
    str += string(i)
    if(i != 10)
        str += ", "
    }
show_message(str)


package main

import "fmt"

func main() {
    for i := 1; ; i++ {
        fmt.Print(i)
        if i == 10 {
            fmt.Println()
            break
        }
        fmt.Print(", ")
    }
}


var out = System.out
for(i in 1..10) {
  if(i > 1) out.print(", ")
  out.print(i)
}


(DEFINE I 1024)

(WHILE (>= I 1)
    (PRINT I)
    (DEFINE I (/ I 2)))


code CrLf=9, IntOut=11;
int I;
[I:= 1024;
while I>0 do
        [IntOut(0, I);  CrLf(0);
        I:= I>>1;       \(same as I/2 for positive I)
        ];
]


i = 1024

while i > 0
  Print i
  i = int(i / 2)
wend

end


const std = @import("std");

pub fn main() void {
    var i: u11 = 1024;
    while (i > 0) : (i /= 2)
        std.debug.print("{}\n", .{i});
}


: test
  9 2 do
    i .
  2 +loop
  ." who do we appreciate?" cr ;


10 DIM A(20)
20 FOR I=1 TO 20
30 A(I)=RND(20)+1
40 NEXT
50 PRINT "THE FULL LIST:";
60 FOR I=1 TO 20
70 PRINT A(I);
80 NEXT
90 PRINT
100 PRINT "THE FULL LIST UP TO THE FIRST ";"INSTANCE OF 20:";
110 FOR I=1 TO 20
120 PRINT A(I);
130 IF A(I)=20 THEN END
140 NEXT


IT'S SHOWTIME
STICK AROUND @NO PROBLEMO
TALK TO THE HAND "SPAM"
CHILL
YOU HAVE BEEN TERMINATED


fun until done change dolast x =
    if done x
      then    dolast x
      else    until done change dolast (change x);       (* iteration/generic loop *)

val isprime = fn n :IntInf.int  =>
let
 fun butlast (_,t)   = t*t > n
 fun divide (n,t)    = n mod t = 0 orelse t*t > n
 fun trymore (n,t)   = (n,t + 2)
in

 n mod 2 <> 0 andalso until divide trymore butlast (n,3)

end;

val loop =  fn () =>
let
 fun butthislast (_,p,_) = rev p
 fun wegot42 (n,_,_)     = n = 43
 fun trymore (n,p,i)     = if isprime i
                                   then ( n+1, (n,i)::p , i+i )
                                   else ( n ,  p, i+1)
in

  until wegot42 trymore butthislast  (1,[],42)

end ;

val printp = fn clist:(int*IntInf.int) list =>
 List.app (fn i=>print ((Int.toString (#1 i) )^" : "^ (IntInf.toString (#2 i) )^"\n")) clist ;


proc isPrime n {
  if {[expr $n % 2] == 0} {
    return [expr $n == 2]
  }
  if {[expr $n % 3] == 0} {
    return [expr $n == 3]
  }
  for {set d 5} {[expr $d * $d] <= $n} {incr d 4} {
    if {[expr $n % $d] == 0} {return 0}
    incr d 2
    if {[expr $n % $d] == 0} {return 0}
  }
  return 1
}

set LIMIT 42

for {set i $LIMIT; set n 0} {$n < $LIMIT} {incr i} {
  if [isPrime $i] {
    incr n
    puts "n=$n, i=$i"
    incr i [expr $i -1]
  }
}


    Sub Main()
        'Loops Increment loop index within loop body - 17/07/2018
        Dim imax, i As Integer
        Dim n As Currency
        imax = 42
        i = 0: n = 42
        Do While i < imax
            If IsPrime(n) Then
                i = i + 1
                Debug.Print ("i=" & RightX(i, 2) & " : " & RightX(Format(n, "#,##0"), 20))
                n = n + n - 1
            End If
            n = n + 1
        Loop
    End Sub 'Main

    Function IsPrime(n As Currency)
        Dim i As Currency
        If n = 2 Or n = 3 Then
            IsPrime = True
        ElseIf ModX(n, 2) = 0 Or ModX(n, 3) = 0 Then
            IsPrime = False
        Else
            i = 5
            Do While i * i <= n
                If ModX(n, i) = 0 Or ModX(n, i + 2) = 0 Then
                    IsPrime = False
                    Exit Function
                End If
                i = i + 6
            Loop
            IsPrime = True
        End If
    End Function 'IsPrime

    Function ModX(a As Currency, b As Currency) As Currency
        ModX = a - Int(a / b) * b
    End Function 'ModX

    Function RightX(c, n)
        RightX = Right(Space(n) & c, n)
    End Function 'RightX


for(i in (1..10)) {
    print i
    if (i == 10) break
    print ', '
}


main :: IO ()
main = forM_ [1 .. 10] $ \n -> do
            putStr $ show n
            putStr $ if n == 10 then "\n" else ", "


for(i = 0; i < 10; i += 2)
    show_message(string(i))


function search_almost_twenty()
% create a 100x100 matrix...
m = unifrnd(0,20, 100,100);
for i = 1:100
  for j = 1:100
    disp( m(i,j) )
    if ( abs(m(i,j) - 20) < 1e-2 )
      return
    endif
  endfor
endfor
endfunction

search_almost_twenty()

% avoiding function, we need a control variable.
m = unifrnd(0,20, 100,100);
innerloopbreak = false;
for i = 1:100
  for j = 1:100
    disp( m(i,j) )
    if ( abs(m(i,j) - 20) < 1e-2 )
      innerloopbreak = true;
      break;
    endif
  endfor
  if ( innerloopbreak )
    break;
  endif
endfor


BEGIN {
  while(1) {
    print "SPAM"
  }
}


Module LoopsIliwlb

    Sub Main()
        'Loops Increment loop index within loop body - 17/07/2018
        Dim imax, i As Int32
        Dim n As Int64
        imax = 42
        i = 0 : n = 42
        While i < imax
            If IsPrime(n) Then
                i = i + 1
                Console.WriteLine("i=" & RightX(i, 2) & " : " & RightX(Format(n, "#,##0"), 20))
                n = n + n - 1
            End If
            n = n + 1
        End While
    End Sub

    Function IsPrime(n As Int64)
        Dim i As Int64
        If n = 2 Or n = 3 Then
            IsPrime = True
        ElseIf (n Mod 2) = 0 Or (n Mod 3) = 0 Then
            IsPrime = False
        Else
            i = 5
            While i * i <= n
                If (n Mod i) = 0 Or (n Mod (i + 2)) = 0 Then
                    IsPrime = False
                    Exit Function
                End If
                i = i + 6
            End While
            IsPrime = True
        End If
    End Function 'IsPrime

    Function RightX(c, n)
        RightX = Right(Space(n) & c, n)
    End Function

End Module


fn is_prime(n u64) bool {
    if n % 2 == 0 {
        return n == 2
    }
    if n % 3 == 0 {
        return n == 3
    }
    mut d := u64(5)
    for d * d <= n {
        if n % d == 0 {
            return false
        }
        d += 2
        if n % d == 0 {
            return false
        }
        d += 4
    }
    return true
}
const limit = 42
fn main() {
    for i, n := u64(limit), 0; n<limit; i++ {
        if is_prime(i) {
            n++
            println("n = ${n:-2}  ${i:19}")
            i += i - 1
        }
    }
}


import "/fmt" for Fmt

var isPrime = Fn.new { |n|
    if (n < 2 || !n.isInteger) return false
    if (n%2 == 0) return n == 2
    if (n%3 == 0) return n == 3
    var d = 5
    while (d*d <= n) {
        if (n%d == 0) return false
        d = d + 2
        if (n%d == 0) return false
        d = d + 4
    }
    return true
}

var count = 0
var i = 42
while (count < 42) {
    if (isPrime.call(i)) {
        count = count + 1
        System.print("%(Fmt.d(2, count)): %(Fmt.dc(18, i))")
        i = 2 * i - 1
    }
    i = i + 1
}


for let i 1; i <= 10; i++
  print i
  if i = 10; break; endif
  print ", "
endfor
println ""


DO i = 1, 10
    WRITE(APPend) i
    IF(i < 10) WRITE(APPend) ", "
ENDDO


U8 i, max = 10;
for (i = 1; i <= max; i++) {
  Print("%d", i);
  if (i == max) break;
  Print(", ");
}
Print("\n");


procedure main()
every writes(i := 1 to 10) do
   if i = 10 then break write()
   else writes(", ")
end


for(i in (2..9).step(2)) {
    print "${i} "
}
println "Who do we appreciate?"


import Control.Monad (forM_)
main = do forM_ [2,4..8] (\x -> putStr (show x ++ ", "))
          putStrLn "who do we appreciate?"


class Step {
  var end:Int;
  var step:Int;
  var index:Int;

  public inline function new(start:Int, end:Int, step:Int) {
    this.index = start;
    this.end = end;
    this.step = step;
  }

  public inline function hasNext() return step > 0 ? end >= index : index >= end;
  public inline function next() return (index += step) - step;
}

class Main {
  static function main() {
    for (i in new Step(2, 8, 2)) {
      Sys.print('$i ');
    }
    Sys.println('WHOM do we appreciate? GRAMMAR! GRAMMAR! GRAMMAR!');
  }
}


for let i 0; i <= 50; let i (i + 5)
  println i
endfor


numbers = .array~new()
do i = 1 to 10
    do j = 1 to 10
        numbers[i,j] = random(1, 20)
    end
end

do i = 1 to numbers~dimension(1)
    do j = 1 to numbers~dimension(2)
        say numbers[i,j]
        if numbers[i,j] = 20 then
            leave i
    end
end


declare
  fun {CreateMatrix Width Height}
    Matrix = {List.make Height}
  in
    for Row in Matrix do
       Row = {List.make Width}
       for X in Row do
          X = {OS.rand} mod 20 +1
       end
    end
    Matrix
  end

  proc {PrintMatrix Matrix}
    %% print until we see 20
     for Row in Matrix break:OuterBreak do
        for X in Row do
           {Show X}
           if X == 20 then {OuterBreak} end
        end
     end
  end
in
  {PrintMatrix {CreateMatrix 10 10}}


      REPEAT
        PRINT "SPAM"
      UNTIL FALSE


get "libhdr"

let start() be writes("SPAM*N") repeat


i = 42
counter = 0
while counter < 42
    if isPrime(i) then
        counter = counter + 1
        print "n = ", counter, chr$(9), i
        i = i + i - 1
    end if
    i = i + 1
wend
end

sub isPrime(v)
    if v < 2  return False
    if mod(v, 2) = 0  return v = 2
    if mod(v, 3) = 0  return v = 3
    d = 5
    while d * d <= v
        if mod(v, d) = 0 then return False else d = d + 2 : fi
    wend
    return True
end sub


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);


output=: verb define
  buffer=: buffer,y
)

loopy=: verb define
  buffer=: ''
  for_n. 1+i.10 do.
    output ":n
    if. n<10 do.
      output ', '
    end.
  end.
  smoutput buffer
)


public static void main(String[] args) {
    for (int i = 1; ; i++) {
        System.out.print(i);
        if (i == 10)
            break;
        System.out.print(", ");
    }
    System.out.println();
}


function loop_plus_half(start, end) {
    var str = '',
        i;
    for (i = start; i <= end; i += 1) {
        str += i;
        if (i === end) {
          break;
        }
        str += ', ';
    }
    return str;
}

alert(loop_plus_half(1, 10));


DO i = 1, 6, 1.25 ! from 1 to 6 step 1.25
   WRITE() i
ENDDO


   every 1 to 10 by 2                       # the simplest case that satisfies the task, step by 2

   every 1 to 10                            # no to, step is by 1 by default
   every EXPR1 to EXPR2 by EXPR3 do EXPR4   # general case - EXPRn can be complete expressions including other generators such as to-by, every's do is optional
   steps := [2,3,5,7]                       # a list
   every i := 1 to 100 by !steps            # . more complex, several passes with each step in the list steps, also we might want to know what value we are at
   every L[1 to 100 by 2]                   # as a list index
   every i := 1 to 100 by (k := !steps)     # . need () otherwise := generates an error
   every 1 to 5 to 10                       # simple case of combined to-by - 1,..,10, 2,..10, ..., 5,..,10
   every 1 to 15 by 2 to 5                  # combined to-by
   every (1 to 15 by 2) to 5                # . made explicit

   every writes( (TO_BY_EXPR) | "\n", " " ) # if you want to see how any of these work


program LoopNested;
uses SysUtils;
const Ni=10; Nj=20;
var
  tab: array[1..Ni,1..Nj] of Integer;
  i, j: Integer;
label loopend;
begin
  for i := 1 to Ni do
    for j := 1 to Nj do
      tab[i,j]:=random(20)+1;
  for i := 1 to Ni do
  begin
    for j := 1 to Nj do
    begin
      WriteLn(tab[i,j]);
      if tab[i,j]=20 then goto loopend
    end
  end;
loopend:
end.


One approach is to construct the answer incrementally:
def loop_plus_half(m;n):
  if m<n then reduce range(m+1;n) as $i (m|tostring; . +  ", " + ($i|tostring))
  else empty
  end;

# An alternative that is shorter and perhaps closer to the task description because it uses range(m;n) is as follows:
def loop_plus_half2(m;n):
  [range(m;n) | if . == m then . else  ", ", . end | tostring] | join("");


for i = 1:10
  print(i)
  i == 10 && break
  print(", ")
end


// version 1.0.6

fun main(args: Array<String>) {
    for (i in 1 .. 10) {
        print(i)
        if (i < 10) print(", ")
    }
}


{def loops_N_plus_one_half
 {lambda {:i :n}
  {if {> :i :n}
   then (end of loop with a dot)
   else {if {= :i 6} then {br}:i else :i}{if {= :i :n} then . else ,}
        {loops_N_plus_one_half {+ :i 1} :n}}}}
-> loops_N_plus_one_half

{loops_N_plus_one_half 0 10}
-> 0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10. (end of loop with a dot)


for(i,2,8,2,
    write(i,", ")
)
write("who do we appreciate?")


    ' who do we appreciate?' ,~ ":  2 * >: i.4
2 4 6 8 who do we appreciate?


for(int i = 2; i <= 8;i += 2){
   System.out.print(i + ", ");
}
System.out.println("who do we appreciate?");


var output = '',
    i;
for (i = 2; i <= 8; i += 2) {
   output += i + ', ';
}
output += 'who do we appreciate?';
document.write(output);


constant s = sq_rand(repeat(repeat(20,20),20))
integer found = 0
for i=1 to 20 do
    for j=1 to 20 do
        printf(1,"%d",s[i][j])
        if s[i][j]=20 then
            found = 1
            exit
        end if
        printf(1,", ")
    end for
    printf(1,"\n")
    if found then exit end if
end for


: ,  dup ", " 2 compress "" join ;
1 do dup 10 != if dup , . 1 + else . break then loop


local(out) = ''
loop(10) => {
    #out->append(loop_count)
    loop_count == 10 ? loop_abort
    #out->append(', ')
}
#out


for "i [1 10]
[
	type :i
	if :i < 10
	[
		type "|, |
	]
]
print


# If your version of jq does not have range/3, use this:
def range(m;n;step): range(0; ((n-m)/step) ) | m + (. * step);

range(2;9;2)


for i in 2:2:8
    print(i, ", ")
end
println("whom do we appreciate?")


// version 1.0.6

fun main(args: Array<String>) {
    for (i in 1 .. 21 step 2) print("$i ")
}


{def loops_for_with_a_specified_step
 {lambda {:a :b :step}
  {if {>= :a :b}
   then (end of loop)
   else :a {loops_for_with_a_specified_step {+ :a :step} :b :step}}}}
-> loops_for_with_a_specified_step

{loops_for_with_a_specified_step 0 10 2}
-> 0 2 4 6 8 (end of loop)

a more simple way:

{S.map {lambda {:i} :i} {S.serie 0 9 2}}
-> 0 2 4 6 8


<?php
for ($i = 0; $i < 10; $i++)
    for ($j = 0; $j < 10; $j++)
        $a[$i][$j] = rand(1, 20);

foreach ($a as $row) {
    foreach ($row as $element) {
        echo " $element";
        if ($element == 20)
            break 2; // 2 is the number of loops we want to break out of
    }
    echo "\n";
}
echo "\n";
?>


(for Lst (make (do 10 (link (make (do 10 (link (rand 1 20)))))))
   (T
      (for N Lst
         (printsp N)
         (T (= N 20) T) ) ) )


while (true)
{
    Console.WriteLine("SPAM");
}


for i =1 to 10
    print i;
    if i =10 then exit for
    print ", ";
next i
end


Section Header

+ name := LOOP_AND_HALF;

Section Public

- main <- (
  + i : INTEGER;

  i := 1;
  {
    i.print;
    i = 10
  }.until_do {
    ", ".print;
    i := i + 1;
  };
  '\n'.print;
);


repeat with n = 1 to 10
    put n after loopn
    if n is not 10 then put comma after loopn
end repeat
put loopn


to comma.list :n
  repeat :n-1 [type repcount type "|, |]
  print :n
end

comma.list 10


for i = 1, 10 do
  io.write(i)
  if i == 10 then break end
  io.write", "
end


: <range>  over iota swap * rot + tuck swap <= select ; : tuck  swap over ;
: >>say.(*)  . ;
1 10 2 <range> >>say.


int main()
{
    // enumerate() normally returns a linearly enumerated array, but
    // allows for the forth argument to specify a function that will
    // be called and return the value that should be in each cell. We
    // create an anonymous function (lambda) that just returns a
    // random value.
    array a = ({});
    for(int i=0; i<20; i++)
        a += ({ enumerate( 20, 1, 1, lambda(){return random(20)+1;} ) });

    // We could use for() and a[x][y] indexing, but foreach is just
    // shorter and easier to use even if the 2D-array becomes less
    // obvious.
 mynestedloops:
    foreach(a, array inner_a) {
        foreach(inner_a, int value) {
            write(value +" ");
            if(value == 20)
                break mynestedloops;
        }
    }
    write("\n");
}


   declare x(20,20) fixed;  /* 16 August 2010. */
   x = random()*20 + 1;
loops:
   do i = 1 to hbound(x,1);
      do j = 1 to hbound(x,2);
         put (x(i,j));
         if x(i,j) = 20 then leave loops;
      end;
      if x(i,j) = 20 then leave;
   end;


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Spam.

       PROCEDURE DIVISION.
           PERFORM UNTIL 1 <> 1
               DISPLAY "SPAM"
           END-PERFORM

           GOBACK
           .


Module Checkit {
      \\ old type loop
      For i=1 to 10
            Print i;
            If i=10 Then Exit For
            Print ", ";
      Next i
      Print
      \\ fast type loop. Continue exit block, without breaking loop.
      For i=1 to 10 {
                  Print i;
                  If i=10 Then Continue
                  Print ", ";
      }
      Print
      Print
      i=0
      {
                  loop  \\ this mark block for loop, each time need to mark
                  i++
                  Print i;
                  If i=10 Then Exit  ' so now we use exit to break loop
                  Print ", ";
      }
      Print
}
Checkit


NEXT=`expr $* + 1`
MAX=10
RES=1

all: 1-n;

$(MAX)-n:
       @echo $(RES)

%-n:
       @-make -f loop.mk $(NEXT)-n MAX=$(MAX) RES=$(RES),$(NEXT)


loop(-to=100, -from=1, -by=2) => {^
    loop_count
    '\r' // for formatting
^}


for {set i 1} {$i < 15} {inc i 3} {print $i}


step = 3
repeat with i = 0 to 10
  put i
  i = i + (step-1)
end repeat


1.to 9 by 2 do { i : INTEGER;
  i.print;
  '\n'.print;
};


; Creating and filling array
Dim Value(10, 5)
For a = 0 To 10
  For b = 0 To 5
    Value(a, b) = Random(19) + 1
  Next
Next
; iterating trough array
For a = 0 To 10
  For b = 0 To 5
    Debug Value(a, b)
    If Value(a, b) = 20
      ; 2 indicates, that there are two nested lopps to break out
      Break 2
    EndIf
  Next
Next


from random import randint

def do_scan(mat):
    for row in mat:
        for item in row:
            print item,
            if item == 20:
                print
                return
        print
    print

mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)


<cfloop condition = "true NEQ false">
  SPAM
</cfloop>


i = 1; s = "";
While[True,
 s = s <> [email protected];
 If[i == 10, Break[]];
 s = s <> ",";
 i++;
 ]
s


for i in 1 to 10 do
(
    format "%" i
    if i == 10 then exit
    format "%" ", "
)


last := 10;
string s; s := "";
for i = 1 upto last:
  s := s & decimal i;
  if i <> last: s := s & ", " fi;
endfor
message s;
end


For i = 1 To 10
  TextWindow.Write(i)
  If i <> 10 Then
    TextWindow.Write(", ")
  EndIf
EndFor
TextWindow.WriteLine("")


repeat with n = 0 to 10 step 2
    put n after loopn
    if n is not 10 then put comma after loopn
end repeat
put loopn


for [i 2 8 2] [type :i type "|, |] print [who do we appreciate?]


Module LoopFor {
      Locale 1036
      Document doc$
      \\ define i as a single
      def single i
      for i=1 to 21 step 5/3
            Print i
            doc$=format$(" {0}", i)
      next i
      doc$={
      }
      \\ make i as a single
      for i=21 to 1 step 5/3
            Print i
            doc$=format$(" {0}", i)
      next i
      clipboard doc$
      report doc$
}
LoopFor


(define random-list
  0 -> []
  M -> [(1+ (RANDOM 20)) | (random-list (1- M))])

(define random-array
  0 _ -> []
  N M -> [(random-list M) | (random-array (1- N) M)])

(define array->list
  _    []                 -> []                                  \ "end outer loop" \
  Stop [[]          | Ra] -> (array->list Stop Ra)               \ "outer loop" \
  Stop [[Stop | _ ] | _ ] -> []                                  \ "break out from inner loop" \
  Stop [[X    | Rl] | Ra] -> [X | (array->list Stop [Rl | Ra])]) \ "inner loop" \

(array->list 20 (random-array 10 10))


  []
  5 times
    [ []
      5 times [ 20 random 1+ join ]
      nested join ]

  dup say "Array contains:" cr
  witheach
    [ witheach
        [ echo sp ]
      cr ]
  cr
  say "Array up to item = 20:" cr
  witheach
    [ false swap
      witheach
        [ dup 20 = iff
            [ drop not conclude ]
          else
            [ echo sp ] ]
      iff conclude
      else cr ]


m <- 10
n <- 10
mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m); mat
done <- FALSE
for(i in seq_len(m))
{
   for(j in seq_len(n))
   {
      cat(mat[i,j])
      if(mat[i,j] == 20)
      {
         done <- TRUE
         break
      }
      cat(", ")
   }
   if(done)
   {
      cat("\n")
      break
   }
}


include "cowgol.coh";

loop
    print("Spam\n");
end loop;


import std.stdio;

void main() {
    while (true)
        writeln("SPAM");
}


1 (dup 10 ==) 'puts! (print succ ", " print!) () linrec


MODULE Loop EXPORTS Main;

IMPORT IO, Fmt;

VAR i := 1;

BEGIN
  LOOP
    IO.Put(Fmt.Int(i));
    IF i = 10 THEN EXIT; END;
    IO.Put(", ");
    i := i + 1;
  END;
  IO.Put("\n");
END Loop.


LOOPHALF
 NEW I
 FOR I=1:1:10 DO
 .WRITE I
 .IF I'=10 WRITE ", "
 QUIT
 ;Alternate
 NEW I FOR I=1:1:10 WRITE I WRITE:I'=10 ", "
 KILL I QUIT


foreach (i in [1 .. 10])
{
    Write(i);
    unless (i == 10) Write(", ");
}


/* NetRexx */
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

  say
  say 'Loops/N plus one half'

  rs = ''
  istart = 1
  iend   = 10
  loop i_ = istart to iend
    rs = rs || ' ' || i_
    if i_ < iend then do
      rs = rs','
      end
    end i_
  say rs.strip()


#lang racket
(define (scan xss)
  (for* ([xs xss]
         [x  xs]
         #:final (= x 20))
    (displayln x)))

(define matrix
  (for/list ([x 10])
    (for/list ([y 10])
      (+ (random 20) 1))))

(scan matrix)


my @a = [ (1..20).roll(10) ] xx *;

LINE: for @a -> @line {
    for @line -> $elem {
        print " $elem";
        last LINE if $elem == 20;
    }
    print "\n";
}
print "\n";


main() {
  while(true) {
    print("SPAM");
  }
}


$ loop:
$  write sys$output "SPAM"
$  goto loop


proc nonrec main() void:
    while true do
        writeln("SPAM")
    od
corp


(for (i 0 10)
  (print i)
  (unless (= i 10)
    (print ", ")))


var s = ""
for i in 1..10:
  s.add $i
  if i == 10: break
  s.add ", "
echo s


10 FOR I=1 TO 10
20 PRINT I;
30 IF I=10 THEN GOTO 50
40 PRINT ",";
50 NEXT


bundle Default {
  class Hello {
    function : Main(args : String[]) ~ Nil {
      for(i := 1; true; i += 1;) {
        i->Print();
        if(i = 10) {
          break;
        };
        ", "->Print();
      };
      '\n'->Print();
    }
  }
}


for i: 1 step 2 thru 10 do print(i);
/* 1
   3
   5
   7 */


for i in range(1,20,4)
    print i
end for


rebol [
	Title: "Loop/Nested"
	URL: http://rosettacode.org/wiki/Loop/Nested
]

; Number formatting.
zeropad: func [pad n][
    n: to-string n  insert/dup n "0" (pad - length? n)  n]

; Initialize random number generator from current time.
random/seed now

; Create array and fill with random numbers, range 1..20.
soup: array [10 10]
repeat row soup [forall row [row/1: random 20]]

print "Loop break using state variable:"
done: no
for y 1 10 1 [
	for x 1 10 1 [
		prin rejoin [zeropad 2 soup/:x/:y  " "]
		if 20 = soup/:x/:y [done: yes  break]
	]
	prin crlf
	if done [break]
]

print [crlf "Loop break with catch/throw:"]
catch [
	for y 1 10 1 [
		for x 1 10 1 [
			prin rejoin [zeropad 2 soup/:x/:y  " "]
			if 20 = soup/:x/:y [throw 'done]
		]
		prin crlf
	]
]
prin crlf


let m = []

for _ in 0 to 9 {
  let n = []
  for _ in 0 to 9 {
    let _ = Js.Array2.push(n, 1 + Js.Math.random_int(0, 20))
  }
  let _ = Js.Array2.push(m, n)
}

try {
  for i in 0 to 9 {
    for j in 0 to 9 {
      Js.log(m[i][j])
      if m[i][j] == 20 { raise(Exit) }
    }
  }
} catch {
| Exit => Js.log("stop")
}


let last = 10 in
for i = 1 to last do
  print_int i;
  if i <> last then
    print_string ", ";
done;
print_newline();


: loopn
| i |
   10 loop: i [ i dup print 10 ifEq: [ break ] "," . ] printcr ;


for N in {List.number 1 10 1} break:Break do
   {System.printInfo N}
   if N == 10 then {Break} end
   {System.printInfo ", "}
end


MODULE ForBy;
  IMPORT InOut;

  VAR
    i: INTEGER;

BEGIN
  FOR i := 0 TO 100 BY 2 DO
    InOut.WriteInt(i, 3);
    InOut.WriteLn
  END
END ForBy.


FOR i := 1 TO 100 BY 2 DO
  IO.Put(Fmt.Int(i) & " ");
END;


/*REXX program loops through a two-dimensional array to search for a  '20'    (twenty). */
parse arg rows cols targ .                       /*obtain optional arguments from the CL*/
if rows=='' | rows==","  then rows=60            /*Rows not specified?  Then use default*/
if cols=='' | cols==","  then cols=10            /*Cols  "      "         "   "     "   */
if targ=='' | targ==","  then targ=20            /*Targ  "      "         "   "     "   */
w=max(length(rows), length(cols), length(targ))  /*W:  used for formatting the output.  */
not= 'not'                                       /* [↓]  construct the 2─dimension array*/
          do     row=1  for rows                 /*ROW  is the 1st dimension of array.  */
              do col=1  for cols                 /*COL   "  "  2nd     "      "   "     */
              @.row.col=random(1, targ)          /*create some positive random integers.*/
              end   /*row*/
          end       /*col*/

          do     r=1  for rows    /* ◄───────────────── now, search for the target {20}.*/
              do c=1  for cols
              say left('@.'r"."c, 3+w+w) '=' right(@.r.c, w)    /*show an array element.*/
              if @.r.c==targ  then do; not=; leave r; end       /*found the targ number?*/
              end   /*c*/
          end       /*r*/

say right( space( 'Target'  not  "found:" )    targ, 33, '─')
                                                 /*stick a fork in it,  we're all done. */


size = 5
array = newlist(size,size)
for row = 1 to size
    for col = 1 to size
        array[row][col] = random(19) + 1
    next
next

for row = 1 to size
    for col = 1 to size
        see "row " + row + " col " + col + "value : " + array[row][col] + nl
        if array[row][col] = 20 exit for row ok
    next
next

func newlist x, y
     if isstring(x) x=0+x ok
     if isstring(y) y=0+y ok
     aList = list(x)
     for t in aList
         t = list(y)
     next
     return aList


[ Infinite loop
  =============

  A program for the EDSAC

  Works with Initial Orders 2 ]

        T56K
        GK

        [email protected]  [ letter shift ]

[  1 ]  [email protected]  [ a += C([email protected]) ]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]
        [email protected]  [ C([email protected]) = a; a = 0 ]
        [email protected]   [ if a >= 0 goto [email protected] ]

[ 10 ]  *F
[ 11 ]  SF
[ 12 ]  PF
[ 13 ]  AF
[ 14 ]  MF
[ 15 ]  @F    [ carriage return ]
[ 16 ]  &F    [ line feed ]

[ 17 ]  PF

        EZPF


open monad io

loop () = do
  putStrLn "SPAM"
  loop ()

loop () ::: IO


public program()
{
    while (true)
    {
        console.writeLine:"spam"
    }
}


program numlist(output);

const MAXNUM: integer = 10;
var
  i: integer;

begin
  { loop 1: w/ if branching }
  for i := 1 to MAXNUM do
    begin
      write(i);
      if i <> MAXNUM then
        write(', ')
    end;
  writeln;
  { loop 2: w/o if branching }
  for i := 1 to MAXNUM-1 do
    write(i, ', ');
  writeln(MAXNUM);
end.


for my $i(1..10) {
    print $i;
    last if $i == 10;
    print ', ';
}
print "\n";


for i=1 to 10 do
    printf(1,"%d",i)
    if i=10 then exit end if
    printf(1,", ")
end for


/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

say
  say 'Loops/For with a specified step'

  loop i_ = -1.4 to 10.6 by 1.7
    say i_.format(3, 1) || '\0'
    end i_
  say


ary = (1..20).to_a.shuffle.each_slice(4).to_a
p ary

catch :found_it do
  for row in ary
    for element in row
      print "%2d " % element
      throw :found_it if element == 20
    end
    puts ","
  end
end

puts "done"


dim a(10,10)
cls
for row = 1 TO 10
        for col = 1 TO 10
                a(row,col) = INT(20 * RND(1) + 1)
        next col
next row

for row = 1 to 10
        for col = 1 to 10
               print a(row, col)
                if a(row, col) = 20 then goto [end]
        next col
next row
[end]
print "At row:";row;" col:";col


defmodule Loops do
  def infinite do
    IO.puts "SPAM"
    infinite
  end
end

Loops.infinite


-module (main).
-export ([main/0]).

main() ->
  io:fwrite( "SPAM~n" ),
  main().


int main(){
   for(int i = 1; i <= 11; i++){
      write(sprintf("%d",i));
      if(i == 10){
         break;
      }
      write(", ");
   }
   write("\n");
}


do i = 1 to 10;
   put edit (trim(i)) (a);
   if i < 10 then put edit (', ') (a);
end;


MODULE LoopForStep;
IMPORT
  Out;
VAR
  i: INTEGER;

BEGIN
  FOR i := 0 TO 10 BY 3 DO
    Out.LongInt(i,0);Out.Ln
  END;
  FOR i := 10 TO 0 BY -3 DO
    Out.LongInt(i,0);Out.Ln
  END
END LoopForStep.


# let for_step a b step fn =
    let rec aux i =
      if i <= b then begin
        fn i;
        aux (i+step)
      end
    in
    aux a
  ;;
val for_step : int -> int -> int -> (int -> 'a) -> unit = <fun>

# for_step 0 8 2  (fun i -> Printf.printf " %d\n" i) ;;
 0
 2
 4
 6
 8
- : unit = ()


use rand::Rng;

extern crate rand;

fn main() {
    let mut matrix = [[0u8; 10]; 10];
    let mut rng = rand::thread_rng();

    for row in matrix.iter_mut() {
        for item in row.iter_mut() {
            *item = rng.gen_range(0, 21);
        }
    }

    'outer: for row in matrix.iter() {
        for &item in row.iter() {
            print!("{:2} ", item);
            if item == 20 { break 'outer }
        }
        println!();
    }
}


class MAIN is
  main is
    a:ARRAY2{INT} := #(10,10);
    i, j :INT;

    RND::seed(1230);
    loop i := 0.upto!(9);
      loop j := 0.upto!(9);
         a[i, j] := RND::int(1, 20);
      end;
    end;

    loopthis ::= true;
    loop i := 0.upto!(9); while!( loopthis );
      loop j := 0.upto!(9);
        #OUT  + " " + a[i, j];
        if a[i, j] = 20 then
	  loopthis := false;
	  break!;
	end;
      end;
    end;
  end;
end;


import scala.util.control.Breaks._
val a=Array.fill(5,4)(scala.util.Random.nextInt(21))
println(a map (_.mkString("[", ", ", "]")) mkString "\n")
breakable {
  for(row <- a; x <- row){
    println(x)
    if (x==20) break
  }
}


while 1 do
    puts(1, "SPAM\n")
end while


// Imperative Solution
while true do
    printfn "SPAM"

// Functional solution
let rec forever () : unit =
    printfn "SPAM"
    forever ()


To run:
Start up.
Write the numbers up to 10 on the console.
Wait for the escape key.
Shut down.

To write the numbers up to a number on the console:
If a counter is past the number, exit.
Convert the counter to a string.
Write the string on the console without advancing.
If the counter is less than the number, write ", " on the console without advancing.
Repeat.


lvars i;
for i from 1 to 10 do
    printf(i, '%p');
    quitif(i = 10);
    printf(', ', '%p');
endfor;
printf('\n', '%p');


for ($i = 1; $i -le 10; $i++) {
    Write-Host -NoNewLine $i
    if ($i -eq 10) {
        Write-Host
        break
    }
    Write-Host -NoNewLine ", "
}


example :-
  between(1,10,Val), write(Val), Val<10, write(', '), fail.
example.


x=1
Repeat
  Print(Str(x))
  x+1
  If x>10: Break: EndIf
  Print(", ")
ForEver


/* Loop from 3 to 9 in steps of 2 */

for ( l = [3:2:9] )  {
  echo (l);
}
echo ("on a double white line.");


for I in 2..8;2 do
   {System.show I}
end
{System.show done}


(call-with-current-continuation
 (lambda (return)
   (for-each (lambda (a)
	       (for-each (lambda (b)
			   (cond ((= 20 b)
				  (newline)
				  (return))
				 (else
				  (display " ")(display b))))
			 a)
	       (newline))
	     array)))


ni=3;nj=4
t=int(rand(ni,nj)*20)+1
for i=1:ni
    for j=1:nj
        printf("%2d ",t(i,j))
        if t(i,j)==11 then break; end
    end
    printf("\n")
    if t(i,j)==11 then break; end
end


class Main
{
  public static Void main ()
  {
    while (true)
    {
      echo ("SPAM")
    }
  }
}


print ( ', '.join(str(i+1) for i in range(10)) )


  10 times
     [ i^ 1+ echo
       i 0 = iff
          conclude done
       say ", " ]


#lang racket
(for ((i (in-range 1 15)))
  (display i)
  #:break (= 10 i)
  (display ", "))


for 1 .. 10 {
    .print;
    last when 10;
    print ', ';
}

print "\n";


fun for(from,to,step) type integer,integer,integer->integer
  t=to.minus(from).divide(step)
  0..t.times(step).plus(from)
  /test it for(1 6 2) -> 1 3 5

for(1 3 5)


for($i=2; $i <= 8; $i += 2) {
  print "$i, ";
}
print "who do we appreciate?\n";


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: i is 0;
    var integer: j is 0;
    var array array integer: a is 10 times 10 times 0;
    const EXCEPTION: FOUND20 is enumlit;
  begin
    for i range 1 to 10 do
      for j range 1 to 10 do
        a[i][j] := rand(1, 20);
      end for;
    end for;
    block
      for i range 1 to 10 do
        for j range 1 to 10 do
          write(a[i][j] lpad 2 <& ", ");
          if a[i][j] = 20 then
            raise FOUND20;
          end if;
        end for;
        writeln;
      end for;
    exception
      catch FOUND20: writeln;
    end block;
  end func;


var arr = 10.of{ 10.of{ 20.irand + 1 } }

for row in arr {
    for num in row {
        "%3d".printf(num);
        num == 20 && goto :OUT
    }
    print "\n"
} @:OUT

print "\n"


   10 WRITE(*,*) 'SPAM'
      GO TO 10
      END


component loops_infinite
  export Executable
  run() = while true do
    println("SPAM")
  end
end


rebol [
    Title: "Loop Plus Half"
    URL: http://rosettacode.org/wiki/Loop/n_plus_one_half
]

repeat i 10 [
	prin i
	if 10 = i [break]
	prin ", "
]
print ""


Red[]

repeat i 10 [
    prin i
    if 10 = i [break]
    prin ", "
]
print ""


set i = 1
set result = ""
while i <= 10
set result = result . i
if i < 10
set result = result . ", "
end if
set i = i + 1
end while
echo result


/*REXX program displays:                 1,2,3,4,5,6,7,8,9,10                           */

     do j=1  to 10
     call charout ,j                             /*write the  DO loop  index  (no LF).  */
     if j<10  then call charout ,","             /*append a comma for one-digit numbers.*/
     end   /*j*/
                                                 /*stick a fork in it,  we're all done. */


for x = 1 to 10 see x if x=10 exit ok see ", " next see nl


for i=2 to 8 by 2 do
    printf(1,"%d, ",i)
end for
printf(1,"who do we appreciate?\n")


<?php
foreach (range(2, 8, 2) as $i)
    echo "$i, ";
echo "who do we appreciate?\n";
?>


|i|

i := 1.
[:exit |
    Transcript showCR:i.
    i == 5 ifTrue:[ exit value:'stopped' ].
    i := i + 1.
] loopWithExit


include "NSLog.incl"

dispatchglobal
  while 1
    NSLog(@"SPAM")
  wend
dispatchend

HandleEvents


Public Sub Main()

Do
  Print "SPAM"
Loop

End


(1..10).each do |i|
  print i
  break if i == 10
  print ", "
end
puts


FOR i = 1 TO 10
  PRINT cma$;i;
  cma$ = " , "
NEXT i


variable more = 0, i;
foreach i ([1:10]) {
  if (more) () = printf(", ");
  printf("%d", i);
  more = 1;
}


var i = 1
while ({
  print(i)
  i < 10
}) {
  print(", ")
  i += 1
}
println()


R  : Prints the odd numbers less than 10.
C  :i = 1
*Loop
T  :#i
C  :i = i + 2
J ( i < 10 )  :*Loop
END:


declare (n, i) fixed binary;

get list (n);
do i = 1 to n by 4;
   put skip list (i);
end;


for(Lo,Hi,Step,Lo)  :- Step>0, Lo=<Hi.
for(Lo,Hi,Step,Val) :- Step>0, plus(Lo,Step,V), V=<Hi, !, for(V,Hi,Step,Val).

example :-
  for(0,10,2,Val), write(Val), write(' '), fail.
example.


matrix a=J(20,20,0)
forv i=1/20 {
	forv j=1/20 {
		matrix a[`i',`j']=runiformint(1,20)
	}
}


let array = [[2, 12, 10, 4], [18, 11, 20, 2]]

loop: for row in array {
    for element in row {
        println(" \(element)")
        if element == 20 { break loop }
    }
}
print("done")


package main

import "fmt"

func main() {
	for {
		fmt.Printf("SPAM\n")
	}
}


(call-with-current-continuation
 (lambda (esc)
   (do ((i 1 (+ 1 i))) (#f)
     (display i)
     (if (= i 10) (esc (newline)))
     (display ", "))))


for i=1:10
    printf("%2d ",i)
    if i<10 then printf(", "); end
end
printf("\n")


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: number is 0;
  begin
    for number range 1 to 10 do
      write(number);
      if number < 10 then
        write(", ")
      end if;
    end for;
    writeln;
  end func;


for (1..10) { |i|
    print i;
    i == 10 && break;
    print ', ';
}

print "\n";


1 to: 10 do: [:n |
    Transcript show: n asString.
    n < 10 ifTrue: [ Transcript show: ', ' ]
]


for i in xrange(2, 9, 2):
    print "%d," % i,
print "who do we appreciate?"


20 times [ i^ echo sp
           2 step ]
cr
1024 times [ i^ 1+ echo sp
             i^ 1+ step ]
cr
1 56 times [ i^ echo sp
             i^ swap step ]
cr


for(a in seq(2,8,2)) {
  cat(a, ", ")
}
cat("who do we appreciate?\n")


#lang racket

(for ([i (in-range 2 9 2)])
  (printf "~a, " i))
(printf "who do we appreciate?~n")


for 2, 4 ... 8 {
    print "$_, ";
}

say 'whom do we appreciate?';


set ary [subst [lrepeat 10 [lrepeat 5 {[expr int(rand()*20+1)]}]]]

try {
    foreach row $ary {
        foreach col $row {
            puts -nonewline [format %3s $col]
            if {$col == 20} {
                throw MULTIBREAK "we're done"
            }
        }
        puts ,
    }
} trap MULTIBREAK {} {}
puts " done"


PROGRAM:LOOP
(A,B)→dim([C])
For(I,1,A)
For(J,1,B)
int(rand*20+1)→[C](I,J)
End
End
For(I,1,A)
For(J,1,B)
Disp [C](I,J)
If [C](I,J)=20
Then
Stop
End
End
End

3→A:4→B:prgmLOOP


loop    str = str lt(i,10) (i = i + 1) :f(out)
        str = str ne(i,10) ',' :s(loop)
out     output = str
end


con
  _clkmode = xtal1 + pll16x
  _clkfreq = 80_000_000

obj
  ser : "FullDuplexSerial.spin"

pub main | n
  ser.start(31, 30, 0, 115200)

  repeat n from 1 to 10
    ser.dec(n)
    if n<10
      ser.str(string(", "))
  ser.str(string(13, 10))

  waitcnt(_clkfreq + cnt)
  ser.stop
  cogstop(0)


forv i=1/10 {
	di `i' _continue
	if `i'<10 {
		di ", " _continue
	}
	else {
		di
	}
}


for var i = 1; ; i++ {
    print(i)
    if i == 10 {
        println()
        break
    }
    print(", ")
}


for {set i 1; set end 10} true {incr i} {
    puts -nonewline $i
    if {$i >= $end} break
    puts -nonewline ", "
}
puts ""


[ 2 4 6 8 ] each "%d, " print
"who do we appreciate?\n" print


for i 2 8 2 [
	prin rejoin [i ", "]]
print "who do we appreciate?"


2.step(8,2) {|n| print "#{n}, "}
puts "who do we appreciate?"


Prgm
  Local mat,i,j
  © randMat(5, 5) exists but returns -9 to 9 rather than 1 to 20
  newMat(5, 5) → mat
  For i,1,rowDim(mat)
    For j,1,colDim(mat)
      rand(20) → mat[i,j]
    EndFor
  EndFor
  Disp mat
  Pause "Press a key."
  ClrIO
  For i,1,rowDim(mat)
    For j,1,colDim(mat)
      If mat[i,j] = 20 Then
        Stop
      Else
        Output i*8, j*18, mat[i,j]
      EndIf
    EndFor
  EndFor
EndPrgm


$$ MODE TUSCRIPT
LOOP
row=""
 LOOP/CLEAR x=1,10
 x=RANDOM_NUMBERS (1,20,1)
 row=APPEND(row," ",x)
  IF (x==20) THEN
   PRINT row
   EXIT,EXIT
  ENDIF
 ENDLOOP
 PRINT row
ENDLOOP


size=10

for ((i=0;i<size;i++)); do
  unset t[@]
  for ((j=0;j<size;j++)); do
    t[$j]=$((RANDOM%20+1))
  done
  a[$i]="${t[*]}"
done

for ((i=0;i<size;i++)); do
  t=(${a[$i]})
  for ((j=0;j<size;j++)); do
    printf "%2d " ${t[$j]}
    [ ${t[$j]} -eq 20 ] && break 2
  done
  echo
done
echo


DO i = 1, 1E20 ! for i with 16 or more digits:  i == i + 1 == loop infinite
    WRITE() "SPAM"
ENDDO


procedure main()
   repeat write("SPAM")
end


Local str
"" → str
For i,1,10
  str & string(i) → str
  If i < 10 Then
    str & "," → str
  EndIf
EndFor
Disp str


    LET I = 1
 10 IF I = 10 THEN PRINT I
    IF I < 10 THEN PRINT I,", "
    IF I = 10 THEN END
    LET I = I + 1
    GOTO 10


$$ MODE TUSCRIPT
line=""
LOOP n=1,10
 line=CONCAT (line,n)
 IF (n!=10) line=CONCAT (line,", ")
ENDLOOP
PRINT line


for(( Z=1; Z<=10; Z++ )); do
    echo -e "$Z\c"
    if (( Z != 10 )); then
        echo -e ", \c"
    fi
done


yes \ | cat -n | head -n 10 | paste -d\  - <(yes , | head -n 9) | xargs echo


fn main() {
  for i in (2..=8).step_by(2) {
    print!("{}", i);
  }
  println!("who do we appreciate?!");
}


for (x; 2; x <= 8; 2)
    print(x, ", ");;
print("who do we appreciate?\n");


data _null_;
do i=1 to 10 by 2;
put i;
end;
run;


void main() {

  int[,] a = new int[10, 10];
  bool broken = false;
  for (int i = 0; i < 10; i++)
    for (int j = 0; j < 10; j++)
      a[i, j] = Random.int_range(0, 21) % 20 + 1;

  for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
      stdout.printf(" %d", a[i, j]);
      if (a[i, j] == 20) {
        broken = true;
        break;
      }
    }
    stdout.printf("\n");
    if (broken) break;
  }
}


Public Sub LoopsNested()
    Dim a(1 To 10, 1 To 10) As Integer
    Randomize
    For i = 1 To 10
        For j = 1 To 10
            a(i, j) = Int(20 * Rnd) + 1
        Next j
    Next i
    For i = 1 To 10
        For j = 1 To 10
            If a(i, j) <> 20 Then
                Debug.Print a(i, j),
            Else
                i = 10 'Upperbound iterator outerloop
                Exit For 'Exit For exits only innerloop
            End If
        Next j
        Debug.Print
    Next i
End Sub


       NOTE THIS IS INTERCAL
       PLEASE ,1 <- #5
       DO ,1 SUB #1 <- #54
       DO ,1 SUB #2 <- #192
       DO ,1 SUB #3 <- #136
       PLEASE ,1 SUB #4 <- #208
       DO ,1 SUB #5 <- #98
       DO COME FROM (1)
       DO READ OUT ,1
(2)    DO ,1 SUB #1 <- #134
(1)    PLEASE ABSTAIN FROM (2)


decl int i
for (set i 1) (< i 11) (inc i)
        out i console
        if (= i 10)
                break
        end if
        out ", " console
end for
out endl console


[loop
   [ [10 =] [puts]
     [true] [dup put ',' put succ loop]
   ] when].


void main() {
  for (int i = 1; i <= 10; i++)
  {
    stdout.printf("%d", i);
    stdout.printf(i == 10 ? "\n" : ", ");
  }
}


Public Sub WriteACommaSeparatedList()
    Dim i As Integer
    Dim a(1 To 10) As String
    For i = 1 To 10
        a(i) = CStr(i)
    Next i
    Debug.Print Join(a, ", ")
End Sub


for (#1 = 1; 1; #1++) {
    Num_Ins(#1, LEFT+NOCR)
    if (#1 == 10) { Break }
    Ins_Text(", ")
}
Ins_Newline


(do ((i 2 (+ i 2)))  ; list of variables, initials and steps -- you can iterate over several at once
  ((>= i 9))         ; exit condition
  (display i)        ; body
  (newline))


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: number is 0;
  begin
    for number range 1 to 10 step 2 do
      writeln(number);
    end for;
  end func;


Module Program
    Sub Main()
        Const ROWS = 10
        Const COLS = 10

        ' Initialize with seed 0 to get deterministic output (may vary across .NET versions, though).
        Dim rand As New Random(0)

        ' VB uses max index array declarations
        Dim nums(ROWS - 1, COLS - 1) As Integer

        For r = 0 To ROWS - 1
            For c = 0 To COLS - 1
                nums(r, c) = rand.Next(0, 21) ' Upper bound is exclusive.
            Next
        Next

        ' MISSING IMPLEMENTATION
    End Sub
End Module


import rand
import rand.seed

fn main() {
    rand.seed(seed.time_seed_array(2))

    mut values := [][]int{len:10, init: []int{len:10}}
    for i in 0..values.len{
        for j in 0..values[0].len {
            values[i][j] = rand.intn(20) or {19} +1
        }
    }
outerloop:
    for i,row in values {
        println('${i:3})')
        for value in row {
            print(' ${value:3}')
            if value==20{
                break outerloop
            }
        }
        println('')
    }
}