CloudFlare suffered a massive security issue affecting all of its customers, including Rosetta Code. All passwords not changed since February 19th 2017 have been expired, and session cookie longevity will be reduced until late March.--Michael Mol (talk) 05:15, 25 February 2017 (UTC)

Loops/Continue

From Rosetta Code
Task
Loops/Continue
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Show the following output using one loop.

1, 2, 3, 4, 5
6, 7, 8, 9, 10


Try to achieve the result by forcing the next iteration within the loop upon a specific condition, if your language allows it.

360 Assembly[edit]

*        Loops/Continue            12/08/2015
LOOPCONT CSECT
USING LOOPCONT,R12
LR R12,R15
BEGIN LA R8,0
SR R5,R5
LA R6,1
LA R7,10
LOOPI BXH R5,R6,ELOOPI for i=1 to 10
LA R3,MVC(R8)
XDECO R5,XDEC
MVC 0(4,R3),XDEC+8
LA R8,4(R8)
LR R10,R5
LA R1,5
SRDA R10,32
DR R10,R1
LTR R10,R10
BNZ COMMA
XPRNT MVC,80
LA R8,0
B NEXTI
COMMA LA R3,MVC(R8)
MVC 0(2,R3),=C', '
LA R8,2(R8)
NEXTI B LOOPI next i
ELOOPI XR R15,R15
BR R14
MVC DC CL80' '
XDEC DS CL16
YREGS
END LOOPCONT
Output:
   1,    2,    3,    4,    5
   6,    7,    8,    9,   10

Ada[edit]

Ada doesn't have a continue statement, so we have to use a goto statement. The previous submitter said continue is not needed. In this example it is indeed not needed, but that is not always the case. An example is a loop where a number of interdependent conditions are checked before executing the main body of the loop. Without a continue statement (or goto), one ends up with nested statements with the main body to the far right of the page.

B.N. You should always try to avoid using a goto, but if you really must, it's there in Ada.

P.S. it is often simplest to place the label on top of the loop, as in real life the need occurs when reading input, so there is no range condition in the loop and we can forgo the null statement.

with Ada.Text_IO;
use Ada.Text_IO;
 
procedure Loop_Continue is
begin
for I in 1..10 loop
Put (Integer'Image(I));
if I = 5 or I = 10 then
New_Line;
goto Continue;
end if;
Put (",");
<<Continue>> --Ada 2012 no longer requires a statement after the label
end loop;
end Loop_Continue;

Agena[edit]

Agena doesn't have a continue statement, conditional statements can be used instead.

for i to 10 do
write( i );
if i % 5 = 0
then write( "\n" )
else write( ", " )
fi
od

Aikido[edit]

foreach i 1..10 {
print (i)
if ((i % 5) == 0) {
println()
continue
}
print (", ")
}

ALGOL 68[edit]

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

ALGOL 68 has no continue reserved word, nor does it need one. The continue reserved word is only syntactic sugar for operations that can be achieved without it as in the following example:

FOR i FROM 1 TO 10 DO
print ((i,
IF i MOD 5 = 0 THEN
new line
ELSE
","
FI
))
OD
Output:
         +1,         +2,         +3,         +4,         +5
         +6,         +7,         +8,         +9,        +10

ALGOL W[edit]

Algol W doesn't have a continue statement - conditional statements can be used instead.

begin
i_w := 1; s_w := 0; % set output format %
for i := 1 until 10 do begin
writeon( i );
if i rem 5 = 0
then write()
else writeon( ", " )
end for_i
end.

AutoHotkey[edit]

Loop, 10 {
Delimiter := (A_Index = 5) || (A_Index = 10) ? "`n":", "
Index .= A_Index . Delimiter
}
MsgBox %Index%

AWK[edit]

BEGIN {
for(i=1; i <= 10; i++) {
printf("%d", i)
if ( i % 5 == 0 ) {
print
continue
}
printf(", ")
}
}

BASIC[edit]

Applesoft BASIC[edit]

 10  FOR I = 1 TO 10
20 PRINT I;
30 IF I - INT (I / 5) * 5 = 0 THEN PRINT : GOTO 50"CONTINUE
40 PRINT ", ";
50 NEXT

BBC BASIC[edit]

BBC BASIC doesn't have a 'continue' statement so the remainder of the loop must be made conditional.

      FOR i% = 1 TO 10
PRINT ; i% ;
IF i% MOD 5 = 0 PRINT ELSE PRINT ", ";
NEXT

Commodore BASIC[edit]

Commodore BASIC also doesn't have a 'continue' statement. In this example, a GOTO statement is used to simulate 'CONTINUE'. However, Commodore BASIC doesn't have a modulo (remainder) operator, so value of I/5 is check against INT(I/5). If they are the same, the remainder is zero.

10 FOR I = 1 TO 10
20 PRINT I;
30 IF INT(I/5) = I/5 THEN PRINT : GOTO 50
40 PRINT ", ";
50 NEXT

FreeBASIC[edit]

' FB 1.05.0 Win64
For i As Integer = 1 To 10
Print Str(i);
If i Mod 5 = 0 Then
Print
Continue For
End If
Print ", ";
Next
 
Print
Sleep
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

Liberty BASIC[edit]

 
for i =1 to 10
if i mod 5 <>0 then print i; ", "; else print i
next i
end
 

PureBasic[edit]

OpenConsole()
 
For i.i = 1 To 10
Print(Str(i))
If i % 5 = 0
PrintN("")
Continue
EndIf
Print(",")
Next
 
Repeat: Until Inkey() <> ""

Run BASIC[edit]

for i = 1 to 10
if i mod 5 <> 0 then print i;", "; else print i
next i

TI-89 BASIC[edit]

count()
Prgm
""→s
For i,1,10
s&string(i)→s
If mod(i,5)=0 Then
Disp s
""→s
Cycle
EndIf
s&", "→s
EndFor
EndPrgm

Ti-89 lacks support for multi-argument display command or controlling the print position so that one can print several data on the same line. The display command (Disp) only accepts one argument and prints it on a single line (causing a line a feed at the end, so that the next Disp command will print in the next line). The solution is appending data to a string (s), using the concatenator operator (&), by converting numbers to strings, and then printing the string at the end of the line.

Visual Basic .NET[edit]

For i = 1 To 10
Console.Write(i)
If i Mod 5 = 0 Then
Console.WriteLine()
Else
Console.Write(", ")
End If
Next

bc[edit]

Requires a bc with the print and continue statements. POSIX bc has not these statements.

Works with: OpenBSD bc
for (i = 1; i <= 10; i++) {
print i
if (i % 5) {
print ", "
continue
}
print "\n"
}
quit

Bracmat[edit]

Bracmat has no continue statement.

( 0:?i
& whl
' ( 1+!i:~>10:?i
& put
$ ( str
$ ( !i
(mod$(!i.5):0&\n|", ")
)
)
)
);

C[edit]

Translation of: C++
for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}

C++[edit]

Translation of: Java
for(int i = 1;i <= 10; i++){
cout << i;
if(i % 5 == 0){
cout << endl;
continue;
}
cout << ", ";
}

C#[edit]

Translation of: Java
using System;
 
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
 
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
 
Console.Write(", ");
}
}
}

Chapel[edit]

for i in 1..10 {
write(i);
if i % 5 == 0 then {
writeln();
continue;
}
write(", ");
}

Clipper[edit]

LOOP keyword is used here instead of continue.

Works as is with Harbour 3.0.0 (Rev. 16951)

FOR i := 1 TO 10
?? i
IF i % 5 == 0
?
LOOP
ENDIF
?? ", "
NEXT

Clojure[edit]

Clojure doesn't have a continue keyword. It has a recur keyword, although I prefer to work with ranges in this case.

(doseq [n (range 1 11)]
(print n)
(if (zero? (rem n 5))
(println)
(print ", ")))

To address the task, however, here's an example loop/recur:

(loop [xs (range 1 11)]
(when-let [x (first xs)]
(print x)
(if (zero? (rem x 5))
(println)
(print ", "))
(recur (rest xs))))

COBOL[edit]

       IDENTIFICATION DIVISION.
PROGRAM-ID. loop-continue.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 i PIC 99.
 
PROCEDURE DIVISION.
PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i
DISPLAY i WITH NO ADVANCING
 
IF FUNCTION MOD(i, 5) = 0
DISPLAY SPACE
EXIT PERFORM CYCLE
END-IF
 
DISPLAY ", " WITH NO ADVANCING
END-PERFORM
 
GOBACK
.

Note: COBOL does have a CONTINUE verb, but this is a no-operation statement used in IF and EVALUATE statements.

ColdFusion[edit]

Remove the leading space from the line break tag.

<cfscript>
for( i = 1; i <= 10; i++ )
{
writeOutput( i );
if( 0 == i % 5 )
{
writeOutput( "< br />" );
continue;
}
writeOutput( "," );
}
</cfscript>

Common Lisp[edit]

Common Lisp doesn't have a continue keyword, but the do iteration construct does use an implicit tagbody, so it's easy to go to any label. Four solutions follow. The first pushes the conditional (whether to print a comma and a space or a newline) into the format string. The second uses the implicit tagbody and go. The third is a do loop with conditionals outside of the output functions.

(do ((i 1 (1+ i))) ((> i 10))
(format t "~a~:[, ~;~%~]" i (zerop (mod i 5))))
 
(do ((i 1 (1+ i))) ((> i 10))
(write i)
(when (zerop (mod i 5))
(terpri)
(go end))
(write-string ", ")
end)
 
(do ((i 1 (1+ i))) ((> i 10))
(write i)
(if (zerop (mod i 5))
(terpri)
(write-string ", ")))

These use the loop iteration form, which does not contain an implicit tagbody (though one could be explicitly included). The first uses an explicit condition to omit the rest of the loop; the second uses block/return-from to obtain the effect of skipping the rest of the code in the block which makes up the entire loop body.

(loop for i from 1 to 10
do (write i)
if (zerop (mod i 5)) do (terpri)
else do (write-string ", "))
 
(loop for i from 1 to 10 do
(block continue
(write i)
(when (zerop (mod i 5))
(terpri)
(return-from continue))
(write-string ", ")))

D[edit]

import std.stdio;
 
void main() {
foreach (i; 1 .. 11) {
write(i);
if (i % 5 == 0) {
writeln();
continue;
}
write(", ");
}
}
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

dc[edit]

The four commands # n J M are special to OpenBSD dc. The # command starts a comment. The n command prints a number without a newline.

Translation of: bc
Works with: OpenBSD dc
1 si		# i = 1
[2Q]sA # A = code to break loop
[[, ]P 1J]sB # B = code to print comma, continue loop
[
li n # print i
li 5 % 0 !=B # call B if i % 5
[
]P # print newline
M # mark from calling B
li 1 + si # i += 1
li 10!<C # continue loop if 10 >= i
]sC li 10!<C # enter loop if 10 >= i

This program uses J and M to force the next iteration of a loop. The nJ command breaks n levels of brackets (like nQ does so), but then skips to the next M command. One can place M at the end of the iteration.

Delphi[edit]

program DoLoop(output);
var
i: integer;
begin
for i := 1 to 10 do
begin
write(i);
if i mod 5 = 0 then
begin
writeln;
continue;
end;
write(', ');
end;
end.
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

DWScript[edit]

var i : Integer;
 
for i := 1 to 10 do begin
Print(i);
if i mod 5 = 0 then begin
PrintLn('');
continue;
end;
Print(', ');
end;

Ela[edit]

Direct Approach[edit]

open monad io
 
loop n =
if n > 10 then do
return ()
else do
putStr (show n)
putStr f
loop (n + 1)
where f | n % 5 == 0 = "\r\n"
| else = ", "
 
_ = loop 1 ::: IO

Using list[edit]

open monad io
 
loop [] = return ()
loop (x::xs) = do
putStr (show x)
putStr f
loop xs
where f | x % 5 == 0 = "\r\n"
| else = ", "
 
_ = loop [1..10] ::: IO

This version is more generic and can work for any given range of values.

Elixir[edit]

defmodule Loops do
def continue do
Enum.each(1..10, fn i ->
IO.write i
IO.write if rem(i,5)==0, do: "\n", else: ", "
end)
end
end
 
Loops.continue
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

Erlang[edit]

%% Implemented by Arjun Sunel
-module(continue).
-export([main/0, for_loop/1]).
 
main() ->
for_loop(1).
 
for_loop(N) when N /= 5 , N <10 ->
io:format("~p, ",[N] ),
for_loop(N+1);
 
for_loop(N) when N >=10->
if N=:=10 ->
io:format("~p\n",[N] )
end;
 
for_loop(N) ->
if N=:=5 ->
io:format("~p\n",[N] ),
for_loop(N+1)
end.
 
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
ok

ERRE[edit]

 
FOR I=1 TO 10 DO
PRINT(I;CHR$(29);)  ! printing a numeric value leaves a blank after it
 ! chr$(29) delete it.....
IF I MOD 5=0 THEN
PRINT
CONTINUE FOR
END IF
PRINT(",";)
END FOR
PRINT
 

Euphoria[edit]

Works with: Euphoria version 4.0.3, 4.0.0 or later
include std\console.e --only for any_key to make running command window easier on windows
 
for i = 1 to 10 do
if remainder(i,5) = 0 then
printf(1, "%d\n", i)
else
printf(1,"%d, ", i)
continue
end if
end for
any_key()

Version without newline after 10 below.

include std\console.e --only for any_key to make running command window easier on windows
 
for i = 1 to 10 do
if remainder(i,5) = 0 then
switch i do
case 10 then
printf(1,"%d ",i)
break --new to euphoria 4.0.0+
case else
printf(1,"%d\n", i)
end switch
 
else
printf(1,"%d, ", i)
continue --new to euphoria 4.0.0+
end if
end for
any_key()
 

F#[edit]

continue is a reserved word, but it has no function. In any case, it is not needed to complete this task.

Translation of: Ada
for i in 1 .. 10 do
printf "%d" i
if i % 5 = 0 then
printf "\n"
else
printf ", "

Factor[edit]

There is no built-in continue in Factor.

1 10 [a,b] [ 
[ number>string write ]
[ 5 mod 0 = "\n" ", " ? write ] bi
] each

Fantom[edit]

While and for loops support continue to jump back to begin the next iteration of the loop.

 
class LoopsContinue
{
public static Void main ()
{
for (Int i := 1; i <= 10; ++i)
{
Env.cur.out.print (i)
if (i % 5 == 0)
{
Env.cur.out.printLine ("")
continue
}
Env.cur.out.print (", ")
}
Env.cur.out.printLine ("")
}
}
 

Forth[edit]

Although this code solves the task, there is no portable equivalent to "continue" for either DO-LOOPs or BEGIN loops.

: main
11 1 do
i dup 1 r.
5 mod 0= if cr else [char] , emit space then
loop ;

Fortran[edit]

Works with: Fortran version 90 and later
do i = 1, 10
write(*, '(I0)', advance='no') i
if ( mod(i, 5) == 0 ) then
write(*,*)
cycle
end if
write(*, '(A)', advance='no') ', '
end do
Works with: Fortran version 77 and later
C     WARNING: This program is not valid ANSI FORTRAN 77 code. It uses
C one nonstandard character on the line labelled 5001. Many F77
C compilers should be okay with it, but it is *not* standard.
C
C It is also worth noting that FORTRAN 77 uses the command CONTINUE,
C but not in the semantic, looping sense of the word. In FORTRAN,
C CONTINUE means "do absolutely nothing." It is a placeholder. If
C anything, it means "continue to the next line."
C
C Python does the same thing with `pass`; C and its family of
C languages, with `{/* do nothing */}`. Write CONTINUE when you need
C to write something but have nothing to write.
C
C This page on Rosetta Code is about a very different "continue"
C statement that tells a loop to go back to the beginning. In
C FORTRAN, we use (you guessed it!) a GOTO to accomplish this.
PROGRAM CONTINUELOOP
INTEGER I
 
DO 10 I = 1, 10
C Is it five or ten?
IF (MOD(I, 5) .EQ. 0) THEN
C If it is, write a newline and no comma.
WRITE (*,5000) I
 
C Continue the loop; that is, skip to the end of the loop.
GOTO 10
ENDIF
 
C Write I with a comma and no newline.
WRITE (*,5001) I
 
C Again, in this case, CONTINUE is completely unrelated to the
C semantic, looping sense of the word.
10 CONTINUE
 
STOP
 
C This will print an integer and a newline (no comma).
5000 FORMAT (I3)
 
C Standard FORTRAN 77 is completely incapable of completing a
C WRITE statement without printing a newline. If you want to print
C five integers in standard code, you have to do something like
C this:
C
C FORMAT (I3, ',', I3, ',', I3, ',', I3, ',', I3)
C
C Writing `1, 2, 3, 4, 5` and then `6, 7, 8, 9, 10` to that format
C would produce the following two lines:
C
C 1, 2, 3, 4, 5
C 6, 7, 8, 9, 10
C
C However, this code exists to demonstrate continuing a FORTRAN 77
C loop and not to demonstrate how to get around its rigidity about
C newlines.
C
C The dollar sign at the end of the format is a nonstandard
C character. It tells the compiler not to print a newline. If you
C are actually using FORTRAN 77, you should figure out what your
C particular compiler accepts. If you are actually using Fortran
C 90 or later, you should replace this line with the commented
C line that follows it.
5001 FORMAT (I3, ',', $)
C5001 FORMAT (I3, ',', ADVANCE='NO')
END

Relying instead upon the looping features of FORMAT[edit]

For historical reasons, 6 is often the default unit number for standard output.

 
WRITE (6,1) (I,I = 1,10)
1 FORMAT (4(1X,I0,","),1X,I0)
END
 

Here the break and continuation comes through the workings of the FORMAT interpreter. The feature 4(etc) means four repetitions of the format items within the brackets, and as each datum from the WRITE statement arrives, it is aligned with the next format item that can receive a datum, the I-format specifier (here I0, which means an integer of only as many digits as are needed for the value) and until such a reciever is encountered, intervening format items are acted upon - 1X means "one space", and the quotes surround a text literal. Accordingly, the first datum generates a space, a one-digit value, and a comma, as does the second and so on. When the sixth datum is received, the end of the format statement has been reached, and the convention is to write the current line and start a new line of output, and further, go back in the FORMAT specification to the first-encountered open-bracket symbol (the rightmost) which in this case is not the beginning of the FORMAT statement but the one that has a repetition count of four in front of it, and, resume interpretation. When the last datum has been accepted, naturally, the line is printed.

An alternative might be FORMAT (4(I2,","),I2) but that would generate

1, 2, 3, 4, 5
6, 7, 8, 9,10

Alternatively, FORMAT (4(I2,","),I2,/,4(I2,","),I3) would do the trick but there would no longer be the loop, break, continue aspect to the interpretation of the FORMAT statement, merely a grinding through a list.

This sort of scheme facilitates a compact way of printing a table with a heading, where the WRITE statement simply pours forth the data and relies on something like FORMAT("heading",/,(complex details for one line)) - thus printing the table line-by-line with only the first line having the heading, a saving on having a write and format statement pair for the heading and a second pair for the table body.

GAP[edit]

for i in [1 .. 11] do
if RemInt(i, 5) = 0 then
Print(i, "\n");
continue;
fi;
Print(i, ", ");
od;
 
# 1, 2, 3, 4, 5
# 6, 7, 8, 9, 10

GML[edit]

for(i = 1; i <= 10; i += 1)
{
show_message(string(i))
i += 1
if(i <= 10)
continue
}

Go[edit]

package main
 
import "fmt"
 
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d", i)
if i%5 == 0 {
fmt.Printf("\n")
continue
}
fmt.Printf(", ")
}
}
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

Groovy[edit]

for (i in 1..10) {
print i
if (i % 5 == 0) {
println ()
continue
}
print ', '
}

Haskell[edit]

As a functional language, it is not idiomatic to have true loops - recursion is used instead. Below is one of many possible implementations of the task. The below code uses a guard (| symbol) to compose functions differently for the two alternative output paths, instead of using continue like in an imperative language.

import Control.Monad (forM)
main = forM [1..10] out
where
out x | x `mod` 5 == 0 = print x
| otherwise = (putStr . (++", ") . show) x

HicEst[edit]

DO i = 1, 10
IF( MOD(i, 5) == 1 ) THEN
WRITE(Format="i3") i
ELSE
WRITE(APPend, Format=" ',', i3 ") i
ENDIF
ENDDO

Icon and Unicon[edit]

The following code demonstrates the use of 'next' (the reserved word for 'continue'):

procedure main()
every writes(x := 1 to 10) do {
if x % 5 = 0 then {
write()
next
}
writes(", ")
}
end

However, the output sequence can be written without 'next' and far more succinctly as:

every writes(x := 1 to 10, if x % 5 = 0 then "\n" else ", ")

Io[edit]

for(i,1,10,
write(i)
if(i%5 == 0, writeln() ; continue)
write(" ,")
)

J[edit]

J is array-oriented, so there is very little need for loops. For example, one could satisfy this task this way:

_2}."1'lq<, >'8!:2>:i.2 5

J does support loops for those times they can't be avoided (just like many languages support gotos for those time they can't be avoided).

3 : 0 ] 10 
z=.''
for_i. 1 + i.y do.
z =. z , ": i
 
if. 0 = 5 | i do.
z 1!:2 ]2
z =. ''
continue.
end.
 
z =. z , ', '
end.
i.0 0
)

Though it's rare to see J code like this.

Java[edit]

for(int i = 1;i <= 10; i++){
System.out.print(i);
if(i % 5 == 0){
System.out.println();
continue;
}
System.out.print(", ");
}

JavaScript[edit]

Using the print() function from Rhino or SpiderMonkey.

var output = "";
for (var i = 1; i <= 10; i++) {
output += i;
if (i % 5 == 0) {
print(output);
output = "";
continue;
}
output += ", ";
}


Stepping back from any assumption that repetitive patterns of computation necessarily entail 'loops', and using a functional idiom of JavaScript, we can make the value of one or more subexpressions in a reduce() fold conditional on any special cases that we define.

For example:

function rng(n) {
return n ? rng(n - 1).concat(n) : [];
}
 
console.log(
rng(10).reduce(
function (a, x) {
return a + x.toString() + (x % 5 ? ', ' : '\n');
}, ''
)
);

Output:

1, 2, 3, 4, 5
6, 7, 8, 9, 10
 

jq[edit]

jq does not have a "continue" statement. In jq 1.4, the simplest way to accomplish the given task is probably as follows:

reduce range(1;11) as $i
(""; . + "\($i)" + (if $i % 5 == 0 then "\n" else ", " end))

Julia[edit]

 
for i in 1:10
print(i)
if i%5 == 0
println()
continue
end
print(", ")
end
 
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

Kotlin[edit]

// version 1.0.6
 
fun main(args: Array<String>) {
for(i in 1 .. 10) {
if (i % 5 == 0) {
println(i)
continue
}
print("$i, ")
}
}
 
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

Lasso[edit]

loop(10) => {^
loop_count
loop_count % 5 ? ', ' | '\r'
loop_count < 100 ? loop_continue
'Hello, World!' // never gets executed
^}

Lingo[edit]

str = ""
repeat with i = 1 to 10
put i after str
if i mod 5 = 0 then
put RETURN after str
next repeat
end if
put ", " after str
end repeat
put str

Lisaac[edit]

1.to 10 do { i : INTEGER;
i.print;
(i % 5 = 0).if { '\n'.print; } else { ','.print; };
};

LiveCode[edit]

repeat with n = 1 to 10
put n
if n is 5 then put return
if n < 10 and n is not 5 then put ","
end repeat

Lua[edit]

for i = 1, 10 do
io.write( i )
if i % 5 == 0 then
io.write( "\n" )
else
io.write( ", " )
end
end

Maple[edit]

for i from 1 to 10 do
printf( "%d", i );
if irem( i, 5 ) = 0 then
printf( "\n" );
next
end if;
printf( ", " )
end do:

This can also be done as follows, but without the use of "next".

for i to 10 do
printf( "%d%s", i, `if`( irem( i, 5 ) = 0, "\n", ", " ) )
end do:

Mathematica[edit]

tmp = "";
For[i = 1, i <= 10, i++,
tmp = tmp <> ToString[i];
If[Mod[i, 5] == 0,
tmp = tmp <> "\n";
,
tmp = tmp <> ", ";
];
];
Print[tmp]

MATLAB / Octave[edit]

Loops are considered slow in Matlab and Octave, it is preferable to vectorize the code.

disp([1:5; 6:10])

or

disp(reshape([1:10],5,2)')

A non-vectorized version of the code is shown below in Octave

for i = 1:10
printf(' %2d', i);
if ( mod(i, 5) == 0 )
printf('\n');
continue
end
end

Maxima[edit]

/* There is no "continue" in Maxima, the easiest is using a "if" instead */
block(
[s: ""],
for n thru 10 do (
s: sconcat(s, n),
if mod(n, 5) = 0 then (
ldisp(s),
s: ""
) else (
s: sconcat(s, ", ")
)
)
)$

MAXScript[edit]

for i in 1 to 10 do
(
format "%" i
if mod i 5 == 0 then
(
format "\n"
continue
) continue
format ", "
)

Insert non-formatted text here

Metafont[edit]

Metafont has no a continue (or similar) keyword. As the Ada solution, we can complete the task just with conditional.

string s; s := "";
for i = 1 step 1 until 10:
if i mod 5 = 0:
s := s & decimal i & char10;
else:
s := s & decimal i & ", "
fi; endfor
message s;
end

Since message append always a newline at the end, we need to build a string and output it at the end, instead of writing the output step by step.

Note: mod is not a built in; like TeX, "bare Metafont" is rather primitive, and normally a set of basic macros is preloaded to make it more usable; in particular mod is defined as

primarydef x mod y = (x-y*floor(x/y)) enddef;

Modula-3[edit]

Modula-3 defines the keyword RETURN as an exception, but when it is used with no arguments it works just like continue in C.

Note, however, that RETURN only works inside a procedure or a function procedure; use EXIT otherwise.

Module code and imports are omitted.

FOR i := 1 TO 10 DO
IO.PutInt(i);
IF i MOD 5 = 0 THEN
IO.Put("\n");
RETURN;
END;
IO.Put(", ");
END;

MOO[edit]

s = "";
for i in [1..10]
s += tostr(i);
if (i % 5 == 0)
player:tell(s);
s = "";
continue;
endif
s += ", ";
endfor

Nemerle[edit]

Translation of: C#
using System;
using System.Console;
using Nemerle.Imperative;
 
module Continue
{
Main() : void
{
foreach (i in [1 .. 10])
{
Write(i);
when (i % 5 == 0) {WriteLine(); continue;}
Write(", ");
}
}
}

NetRexx[edit]

/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
say
say 'Loops/Continue'
 
nul = '\-'
loop i_ = 1 to 10
say i_.right(2) || nul
if i_ // 5 = 0 then do
say
iterate i_
end
say ', ' || nul
 
end i_
 

NewLISP[edit]

(for (i 1 10)
(print i)
(if (= 0 (% i 5))
(println)
(print ", ")))

Nim[edit]

Translation of: Python
for i in 1..10:
if i mod 5 == 0:
echo i
continue
stdout.write i, ","

OCaml[edit]

There is no continue statement for for loops in OCaml, but it is possible to achieve the same effect with an exception.

# for i = 1 to 10 do
try
print_int i;
if (i mod 5) = 0 then raise Exit;
print_string ", "
with Exit ->
print_newline()
done
;;
1, 2, 3, 4, 5
6, 7, 8, 9, 10
- : unit = ()

Though even if the continue statement does not exist, it is possible to add it with camlp4.

Octave[edit]

v = "";
for i = 1:10
v = sprintf("%s%d", v, i);
if ( mod(i, 5) == 0 )
disp(v)
v = "";
continue
endif
v = sprintf("%s, ", v);
endfor

Oforth[edit]

: loopCont 
| i |
10 loop: i [
i dup print 5 mod ifZero: [ printcr continue ]
"," .
] ;

Oz[edit]

By using the "continue" feature of the for-loop, we bind C to a nullary procedure which, when invoked, immediately goes on to the next iteration of the loop.

for I in 1..10 continue:C do
{System.print I}
if I mod 5 == 0 then
{System.printInfo "\n"}
{C}
end
{System.printInfo ", "}
end

PARI/GP[edit]

for(n=1,10,
print1(n);
if(n%5 == 0, print();continue);
print1(", ")
)

Pascal[edit]

See Delphi

Perl[edit]

foreach (1..10) {
print $_;
if ($_ % 5 == 0) {
print "\n";
next;
}
print ', ';
}

It is also possible to use a goto statement to jump over the iterative code section for a particular loop:

foreach (1..10) {
print $_;
if ($_ % 5 == 0) {
print "\n";
goto MYLABEL;
}
print ', ';
MYLABEL:
}

Perl 6[edit]

Translation of: Perl
Works with: Rakudo Star version 2010.08
for 1 .. 10 {
.print;
if $_ %% 5 {
print "\n";
next;
}
print ', ';
}

or without using a loop:

$_.join(", ").say for [1..5], [6..10];

Phix[edit]

for i=1 to 10 do
printf(1,"%d", i)
if remainder(i,5)=0 then
printf(1, "\n")
continue
end if
printf(1,", ")
end for
{} = wait_key()

PHP[edit]

for ($i = 1; $i <= 10; $i++) {
echo $i;
if ($i % 5 == 0) {
echo "\n";
continue;
}
echo ', ';
}

PicoLisp[edit]

PicoLisp doesn't have an explicit 'continue' functionality. It can always be emulated with a conditional expression.

(for I 10
(print I)
(if (=0 (% I 5))
(prinl)
(prin ", ") ) )

Pike[edit]

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

PL/I[edit]

loop:
do i = 1 to 10;
put edit (i) (f(3));
if mod(i,5) = 0 then do; put skip; iterate loop; end;
put edit (', ') (a);
end;

Pop11[edit]

lvars i;
for i from 1 to 10 do
printf(i, '%p');
if i rem 5 = 0 then
printf('\n');
nextloop;
endif;
printf(', ')
endfor;

PowerShell[edit]

Translation of: C
for ($i = 1; $i -le 10; $i++) {
Write-Host -NoNewline $i
if ($i % 5 -eq 0) {
Write-Host
continue
}
Write-Host -NoNewline ", "
}

Python[edit]

for i in xrange(1,11):
if i % 5 == 0:
print i
continue
print i, ",",

R[edit]

Translation of: C++
for(i in 1:10)
{
cat(i)
if(i %% 5 == 0)
{
cat("\n")
next
}
cat(", ")
}

Racket[edit]

It is possible to skip loop iterations in Racket, but an explicit continue construct is rarely used:

 
#lang racket
 
;; Idiomatic way
(for ([i (in-range 1 11)])
(if (= (remainder i 5) 0)
(printf "~a~n" i)
(printf "~a, " i)))
 
;; Forces a skip, but not idiomatic because
;; the logic is less obvious
(for ([i (in-range 1 11)]
#:unless (and (= (remainder i 5) 0)
(printf "~a~n" i)))
(printf "~a, " i))
 

REBOL[edit]

rebol [
Title: "Loop/Continue"
Author: oofoe
Date: 2010-01-05
URL: http://rosettacode.org/wiki/Loop/Continue
]

 
; REBOL does not provide a 'continue' word for loop constructs,
; however, you may not even miss it:
 
print "One liner (compare to ALGOL 68 solution):"
repeat i 10 [prin rejoin [i either 0 = mod i 5 [crlf][", "]]]
 
print [crlf "Port of ADA solution:"]
for i 1 10 1 [
prin i
either 0 = mod i 5 [
prin newline
][
prin ", "
]
]
Output:
One liner (compare to ALGOL 68 solution):
1, 2, 3, 4, 5
6, 7, 8, 9, 10

Port of ADA solution:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

REXX[edit]

version 1[edit]

(This program could be simpler by using a   then/else   construct, but an   iterate   was used to conform to the task.)

/*REXX program  illustrates  an example of a   DO   loop with an  ITERATE  (continue).  */
 
do j=1 for 10 /*this is equivalent to: DO J=1 TO 10 */
call charout , j /*write the integer to the terminal. */
if j//5\==0 then do /*Not a multiple of five? Then ··· */
call charout , ", " /* write a comma to the terminal, ··· */
iterate /* ··· & then go back for next integer.*/
end
say /*force REXX to display on next line. */
end /*j*/
/*stick a fork in it, we're all done. */

Program note:   the comma (,) immediately after the   charout   BIF indicates to use the terminal output stream.

output

1, 2, 3, 4, 5
6, 7, 8, 9, 10

version 2[edit]

/*REXX program  illustrates  an example of a   DO   loop with an  ITERATE  (continue).  */
$= /*nullify the variable used for display*/
do j=1 for 10 /*this is equivalent to: DO J=1 TO 10 */
$=$ || j', ' /*append the integer to a placeholder. */
if j//5==0 then say left($, length($) - 2) /*Is J a multiple of five? Then SAY.*/
if j==5 then $= /*start the display line over again. */
end /*j*/
/*stick a fork in it, we're all done. */

output   is the same as the 1st REXX version.

Ring[edit]

 
for i = 1 TO 10
see i
if i % 5 = 0
see nl
loop
ok
see ", "
next
 

Ruby[edit]

for i in 1..10 do
print i
if i % 5 == 0 then
puts
next
end
print ', '
end

The "for" look could be written like this:

(1..10).each do |i| ...
1.upto(10) do |i| ...
10.times do |n| i=n+1; ...

Without meeting the criteria (showing loop continuation), this task could be written as:

(1..10).each_slice(5){|ar| puts ar.join(", ")}

Rust[edit]

fn main() {
for i in 1..10+1 {
print!("{}", i);
if i % 5 == 0 {
print!("\n");
continue;
}
print!(", ");
}
}

Salmon[edit]

iterate (x; [1...10])
{
print(x);
if (x % 5 == 0)
{
print("\n");
continue;
};
print(", ");
};

Sather[edit]

There's no continue! in Sather. The code solve the task without forcing a new iteration.

class MAIN is
main is
i:INT;
loop i := 1.upto!(10);
#OUT + i;
if i%5 = 0 then
#OUT + "\n";
else
#OUT + ", ";
end;
end;
end;
end;

Scala[edit]

Scala doesn't have a continue keyword. However, you may not even miss it, if could be used here.

The intuitive way[edit]

for (i <- 1 to 10) {
print(i)
if (i % 5 == 0) println() else print(", ")
}

Functional solution[edit]

Thinking In Scala© says: we avoid for loops and handle it the Functional way:

  1. Create a Range 1..10 included
  2. Split the range after converting to a List to a pair of List's
  3. A List of the elements of pair of will be created: List(List(1,2,3,4,5),List(6,7,8,9,10))
  4. The map makes for both elements in the List a conversion to a comma separated String, yielding a List of two Strings.
  5. Both comma separated strings will be separated by an EOL
  val a = (1 to 10 /*1.*/ ).toList.splitAt(5) //2.
println(List(a._1, a._2) /*3.*/ .map(_.mkString(", ") /*4.*/ ).mkString("\n") /*5.*/ )

Scheme[edit]

(define (loop i)
(if (> i 10) 'done
(begin
(display i)
(cond ((zero? (modulo i 5))
(newline) (loop (+ 1 i)))
(else (display ", ")
(loop (+ 1 i)))))))

Scilab[edit]

Works with: Scilab version 5.5.1
for i=1:10
printf("%2d ",i)
if modulo(i,5)~=0 then
printf(", ")
continue
end
printf("\n")
end
Output:
 1 ,  2 ,  3 ,  4 ,  5 
 6 ,  7 ,  8 ,  9 , 10 

Sidef[edit]

for i in (1..10) {
print i
if (i %% 5) {
print "\n"
next
}
print ', '
}

Simula[edit]

Works with: SIMULA-67
! Loops/Continue - simula67 - 07/03/2017;
begin
integer i;
for i:=1 step 1 until 10 do begin
outint(i,5);
if mod(i,5)=0 then begin
outimage;
goto loop
end;
outtext(", ");
loop:
end
end
Output:
    1,     2,     3,     4,     5
    6,     7,     8,     9,    10


Suneido[edit]

ob = Object()
for (i = 1; i <= 10; ++i)
{
ob.Add(i)
if i is 5
{
Print(ob.Join(','))
ob = Object()
}
}
Print(ob.Join(','))
Output:
1,2,3,4,5
6,7,8,9,10
ok

Swift[edit]

for i in 1...10 {
print(i)
if i%5 == 0 {
println()
continue
}
print(", ")
}
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

Tcl[edit]

for {set i 1} {$i <= 10} {incr i} {
puts -nonewline $i
if {$i % 5 == 0} {
puts ""
continue
}
puts -nonewline ", "
}

TUSCRIPT[edit]

 
$$ MODE TUSCRIPT
numbers=""
LOOP n=1,10
numbers=APPEND (numbers,", ",n)
rest=n%5
IF (rest!=0) CYCLE
PRINT numbers
numbers=""
ENDLOOP
 
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

UnixPipes[edit]

yes \ | cat -n | head -n 10 | xargs -n 5 echo | tr ' ' ,

UNIX Shell[edit]

Z=1
while (( Z<=10 )); do
echo -e "$Z\c"
if (( Z % 5 != 0 )); then
echo -e ", \c"
else
echo -e ""
fi
(( Z++ ))
done
Works with: Bash
for ((i=1;i<=10;i++)); do
echo -n $i
if [ $((i%5)) -eq 0 ]; then
echo
continue
fi
echo -n ", "
done

Ursa[edit]

Translation of: Python
decl int i
for (set i 1) (< i 11) (inc i)
if (= (mod i 5) 0)
out i endl console
continue
end if
out i ", " console
end for

Vedit macro language[edit]

for (#1 = 1; #1 <= 10; #1++) {
Num_Type(#1, LEFT+NOCR)
if (#1 % 5 == 0) {
Type_Newline
Continue
}
Message(", ")
}


XPL0[edit]

Like Ada and ALGOL there's no 'continue' command. The task is solved very simply anyway. The commands 'int' and 'rem' are shown spelled out here. Only the first three characters of a command are required.

code CrLf=9, IntOut=11, Text=12;
integer N;
for N:= 1 to 10 do
[IntOut(0, N); if remainder(N/5) \#0\ then Text(0, ", ") else CrLf(0)]
Output:
1, 2, 3, 4, 5
6, 7, 8, 9, 10

zkl[edit]

foreach n in ([1..10]){print(n); if(n%5==0){println(); continue;} print(", ")}
// or foreach n in ([1..10]){print(n,(n%5) and ", " or "\n")}