Loops/Continue: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Perl 6.)
m (Fixed lang tags.)
Line 8: Line 8:
Ada 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.
Ada 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.


<lang ada>
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
with Ada.Text_Io; use Ada.Text_Io;


procedure Loop_Continue is
procedure Loop_Continue is
Line 21: Line 20:
end if;
end if;
end loop;
end loop;
end Loop_Continue;
end Loop_Continue;</lang>
</lang>
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
[[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:
[[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:
<lang algol68>FOR i FROM 1 TO 10 DO
<pre>
FOR i FROM 1 TO 10 DO
print ((i,
print ((i,
IF i MOD 5 = 0 THEN
IF i MOD 5 = 0 THEN
Line 34: Line 31:
FI
FI
))
))
OD
OD</lang>
</pre>
Output:
Output:
<lang algol68>+1, +2, +3, +4, +5
<pre>
+1, +2, +3, +4, +5
+6, +7, +8, +9, +10</lang>
+6, +7, +8, +9, +10
</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>
<lang autohotkey>Loop, 10 {
Loop, 10 {
Delimiter := (A_Index = 5) || (A_Index = 10) ? "`n":", "
Delimiter := (A_Index = 5) || (A_Index = 10) ? "`n":", "
Index .= A_Index . Delimiter
Index .= A_Index . Delimiter
}
}
MsgBox %Index%
MsgBox %Index%</lang>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
Line 108: Line 100:
=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
Remove the leading space from the line break tag.
Remove the leading space from the line break tag.
<cfscript>
<lang cfm><cfscript>
for( i = 1; i <= 10; i++ )
for( i = 1; i <= 10; i++ )
{
{
writeOutput( i );
writeOutput( i );
if( 0 == i % 5 )
if( 0 == i % 5 )
{
{
writeOutput( "< br />" );
writeOutput( "< br />" );
continue;
continue;
}
}
writeOutput( "," );
writeOutput( "," );
}
}
</cfscript>
</cfscript></lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 179: Line 171:
=={{header|Forth}}==
=={{header|Forth}}==
Although this code solves the task, there is no portable equivalent to "continue" for either DO-LOOPs or BEGIN loops.
Although this code solves the task, there is no portable equivalent to "continue" for either DO-LOOPs or BEGIN loops.
<lang forth>
<lang forth>: main
: main
11 1 do
11 1 do
i dup 1 r.
i dup 1 r.
5 mod 0= if cr else [char] , emit space then
5 mod 0= if cr else [char] , emit space then
loop ;
loop ;</lang>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 202: Line 192:
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.
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.


<lang haskell>
<lang haskell>import Control.Monad (forM)
import Control.Monad (forM)
main = forM [1..10] out
main = forM [1..10] out
where
where
Line 215: Line 204:


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).
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).
<lang j>3 : 0 ] 10
<pre>
3 : 0 ] 10
z=.''
z=.''
for_i. 1 + i.y do.
for_i. 1 + i.y do.
Line 230: Line 218:
end.
end.
i.0 0
i.0 0
)
)</lang>
</pre>


Though it's rare to see J code like this.
Though it's rare to see J code like this.
Line 261: Line 248:


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>
<lang Lisaac>1.to 10 do { i : INTEGER;
1.to 10 do { i : INTEGER;
i.print;
i.print;
(i % 5 = 0).if { '\n'.print; } else { ','.print; };
(i % 5 = 0).if { '\n'.print; } else { ','.print; };
};
};</lang>
</lang>


=={{header|Mathematica}}==
=={{header|Mathematica}}==
<lang Mathematica>
<lang Mathematica>tmp = "";
tmp = "";
For[i = 1, i <= 10, i++,
For[i = 1, i <= 10, i++,
tmp = tmp <> ToString[i];
tmp = tmp <> ToString[i];
Line 279: Line 263:
];
];
];
];
Print[tmp]
Print[tmp]</lang>
</lang>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>for i in 1 to 10 do
<pre>
for i in 1 to 10 do
(
(
format "%" i
format "%" i
Line 293: Line 275:
) continue
) continue
format ", "
format ", "
)</lang>
)
</pre>


=={{header|Metafont}}==
=={{header|Metafont}}==
Line 322: Line 303:


Module code and imports are omitted.
Module code and imports are omitted.
<lang modula3>FOR i := 1 TO 10 DO
<pre>
FOR i := 1 TO 10 DO
IO.PutInt(i);
IO.PutInt(i);
IF i MOD 5 = 0 THEN
IF i MOD 5 = 0 THEN
Line 330: Line 310:
END;
END;
IO.Put(", ");
IO.Put(", ");
END;
END;</lang>
</pre>


=={{header|MOO}}==
=={{header|MOO}}==
Line 408: Line 387:


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>lvars i;
<pre>
lvars i;
for i from 1 to 10 do
for i from 1 to 10 do
printf(i, '%p');
printf(i, '%p');
Line 417: Line 395:
endif;
endif;
printf(', ')
printf(', ')
endfor;
endfor;</lang>
</pre>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Line 440: Line 417:
=={{header|R}}==
=={{header|R}}==
Translated from C++.
Translated from C++.
<lang R>
<lang R>for(i in 1:10)
for(i in 1:10)
{
{
cat(i)
cat(i)
Line 450: Line 426:
}
}
cat(", ")
cat(", ")
}</lang>
}
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
Line 490: Line 465:


=={{header|UnixPipes}}==
=={{header|UnixPipes}}==
yes \ | cat -n | head -n 10 | xargs -n 5 echo | tr ' ' ,
<lang bash>yes \ | cat -n | head -n 10 | xargs -n 5 echo | tr ' ' ,</lang>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<lang vedit>
<lang vedit>for (#1 = 1; #1 <= 10; #1++) {
for (#1 = 1; #1 <= 10; #1++) {
Num_Type(#1, LEFT+NOCR)
Num_Type(#1, LEFT+NOCR)
if (#1 % 5 == 0) {
if (#1 % 5 == 0) {
Line 501: Line 475:
}
}
Message(", ")
Message(", ")
}</lang>
}
</lang>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==

Revision as of 21:50, 20 November 2009

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

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 whitin the loop upon a specific condition, if your language allows it.

Ada

Ada 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.

<lang ada>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 mod 5 = 0 then
        New_Line;
     else
        Put(",");
     end if;
  end loop;

end Loop_Continue;</lang>

ALGOL 68

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: <lang algol68>FOR i FROM 1 TO 10 DO

 print ((i, 
   IF i MOD 5 = 0 THEN
     new line
   ELSE
     ","
   FI
 ))

OD</lang> Output: <lang algol68>+1, +2, +3, +4, +5

        +6,         +7,         +8,         +9,        +10</lang>

AutoHotkey

<lang autohotkey>Loop, 10 {

 Delimiter := (A_Index = 5) || (A_Index = 10) ? "`n":", "
 Index .= A_Index . Delimiter

} MsgBox %Index%</lang>

AWK

<lang awk>BEGIN {

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

}</lang>

C

Translation of: C++

<lang c>for(int i = 1;i <= 10; i++){

  printf("%d", i);
  if(i % 5 == 0){
     printf("\n");
     continue;
  }
  printf(", ");

}</lang>

C++

Translation of: Java

<lang cpp>for(int i = 1;i <= 10; i++){

  cout << i;
  if(i % 5 == 0){
     cout << endl;
     continue;
  }
  cout << ", ";

}</lang>

C#

Translation of: Java

<lang csharp>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(", ");
       }
   }

}</lang>

ColdFusion

Remove the leading space from the line break tag. <lang cfm><cfscript>

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

</cfscript></lang>

Common Lisp

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. <lang lisp>(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 ", ")))</lang>

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.


<lang lisp>(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 ", ")))</lang>

D

<lang d>for(int i = 1;i <= 10; i++){

 writef(i);
 if(i % 5 == 0){
   writefln();
   continue;
 }
 writef(", ");

}</lang>

E

<lang e>for i in 1..10 {

   print(i)
   if (i %% 5 == 0) { 
       println()
       continue
   }
   print(", ")

}</lang>

Forth

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

 11 1 do
   i dup 1 r.
   5 mod 0= if cr else [char] , emit space then
 loop ;</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran>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</lang>

Haskell

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.

<lang haskell>import Control.Monad (forM) main = forM [1..10] out

   where
     out x | (x `mod` 5 == 0) = (putStrLn . show) x
           | otherwise = (putStr . (++", ") . show) x</lang>

J

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). <lang j>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
  )</lang>

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


Java

<lang java>for(int i = 1;i <= 10; i++){

  System.out.print(i);
  if(i % 5 == 0){
     System.out.println();
     continue;
  }
  System.out.print(", ");

}</lang>

JavaScript

Using the print() function from Rhino or SpiderMonkey. <lang javascript>var output = ""; for (var i = 1; i <= 10; i++) {

 output += i; 
 if (i % 5 == 0) {
   print(output);
   output = "";
   continue;
 } 
 output += ", ";

}</lang>

Lisaac

<lang Lisaac>1.to 10 do { i : INTEGER;

 i.print;
 (i % 5 = 0).if { '\n'.print; } else { ','.print; };

};</lang>

Mathematica

<lang Mathematica>tmp = ""; For[i = 1, i <= 10, i++,

 tmp = tmp <> ToString[i];
 If[Mod[i, 5] == 0,
  tmp = tmp <> "\n";
  ,
  tmp = tmp <> ", ";
  ];
 ];

Print[tmp]</lang>

MAXScript

<lang maxscript>for i in 1 to 10 do (

   format "%" i
   if mod i 5 == 0 then
   (
       format "\n"
       continue
   )   continue
   format ", "

)</lang>

Metafont

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

<lang metafont>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</lang>

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

<lang metafont>primarydef x mod y = (x-y*floor(x/y)) enddef;</lang>

Modula-3

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. <lang modula3>FOR i := 1 TO 10 DO

 IO.PutInt(i);
 IF i MOD 5 = 0 THEN
   IO.Put("\n");
   RETURN;
 END;
 IO.Put(", ");

END;</lang>

MOO

<lang moo>s = ""; for i in [1..10]

 s += tostr(i);
 if (i % 5 == 0)
   player:tell(s);
   s = "";
   continue;
 endif
 s += ", ";

endfor</lang>

OCaml

There is no continue statement for for loops in OCaml, but it is possible to achieve the same effect with an exception. <lang ocaml># 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 = ()</lang> Though even if the continue statement does not exist, it is possible to add it with camlp4.

Octave

<lang octave>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</lang>

Perl

<lang perl>foreach (1..10) {

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

}</lang>

Perl 6

Translation of: Perl
Works with: Rakudo version #21 "Seattle"

<lang perl6>for 1 .. 10 {

   .print;
   unless $_ % 5 {
       say ;
       next;
   }
   print ', ';

}</lang>

PHP

<lang php>for ($i = 1; $i <= 10; $i++) {

   echo $i;
   if ($i % 5 == 0) {
       echo "\n";
       continue;
   }
   echo ', ';

}</lang>

Pop11

<lang pop11>lvars i; for i from 1 to 10 do

  printf(i, '%p');
  if i rem 5 = 0 then
      printf('\n');
      nextloop;
  endif;
  printf(', ')

endfor;</lang>

PowerShell

Translation of: C

<lang powershell>for ($i = 1; $i -le 10; $i++) {

   Write-Host -NoNewline $i
   if ($i % 5 -eq 0) {
       Write-Host
       continue
   }
   Write-Host -NoNewline ", "

}</lang>

Python

<lang python>for i in xrange(1,11):

   if i % 5 == 0:
       print i
       continue
   print i, ",",</lang>

R

Translated from C++. <lang R>for(i in 1:10) {

  cat(i)
  if(i %% 5 == 0) 
  {
     cat("\n")
     next
  }
  cat(", ")

}</lang>

REXX

(Remember that there exists implementations of the REXX language that needs that the source begins with /*, i.e. with a comment) <lang rexx>do i = 1 to 10

 call charout ,i", "
 if i//5 = 0 then do
   say
   iterate
 end

end</lang>

Ruby

<lang ruby>for i in 1..10 do

  print i
  if i % 5 == 0 then
     puts
     next
  end
  print ', '

end</lang> The "for" look could be written like this: <lang ruby>(1..10).each do |i| ... 1.upto(10) do |i| ... 10.times do |n| i=n+1; ...</lang> Without meeting the criteria (showing loop continuation), this task could be written as: <lang ruby>1.upto(10) {|i| print "%d%s" % [i, i%5==0 ? "\n" : ", "]}</lang>

Tcl

<lang tcl>for {set i 1} {$i <= 10} {incr i} {

  puts -nonewline $i
  if {$i % 5 == 0} {
     puts ""
     continue
  }
  puts -nonewline ", "

}</lang>

UnixPipes

<lang bash>yes \ | cat -n | head -n 10 | xargs -n 5 echo | tr ' ' ,</lang>

Vedit macro language

<lang vedit>for (#1 = 1; #1 <= 10; #1++) {

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

}</lang>

Visual Basic .NET

<lang vbnet>For i = 1 To 10

   Console.Write(i)
   If i Mod 5 = 0 Then
       Console.WriteLine()
   Else
       Console.Write(", ")
   End If

Next</lang>