Loops/For

Revision as of 01:43, 27 July 2010 by 24.41.5.170 (talk) (added Clojure version)

“For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.

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

For this task, show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another:

*
**
***
****
*****

ActionScript

<lang actionscript>for (var i:int = 1; i <= 5; i++) {

   for (var j:int = 1; j <= i)
       trace("*");

}</lang>

Ada

<lang ada>for I in 1..5 loop

  for J in 1..I loop
     Put("*");
  end loop;
  New_Line;

end loop;</lang>

ALGOL 68

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

<lang algol68>FOR i TO 5 DO

  TO i DO
     print("*")
  OD;
 print(new line)

OD</lang> Output:

*
**
***
****
*****

AmigaE

<lang amigae>PROC main()

 DEF i, j
 FOR i := 1 TO 5
   FOR j := 1 TO i DO WriteF('*')
   WriteF('\n')
 ENDFOR

ENDPROC</lang>

AppleScript

<lang AppleScript>set x to return repeat with i from 1 to 5 repeat with j from 1 to i set x to x & "*" end repeat set x to x & return end repeat return x</lang>Output:<lang AppleScript>"

" </lang>

AutoHotkey

<lang AutoHotkey>Gui, Add, Edit, vOutput r5 w100 -VScroll ; Create an Edit-Control Gui, Show ; Show the window Loop, 5 ; loop 5 times {

 Loop, %A_Index% ; A_Index contains the Index of the current loop
 {
   output .= "*" ; append an "*" to the output var
   GuiControl, , Output, %Output% ; update the Edit-Control with the new content
   Sleep, 500 ; wait some(500ms) time, [just to show off]
 }
 Output .= (A_Index = 5) ? "" : "`n" ; append a new line to the output if A_Index is not "5"

} Return ; End of auto-execution section</lang>

AWK

<lang awk>BEGIN {

 for(i=1; i < 6; i++) {
   for(j=1; j <= i; j++ ) {
     printf "*"
   }
   print
 }

}</lang>

BASIC

Works with: QuickBasic version 4.5

<lang qbasic>for i = 1 to 5

  for j = 1 to i
     print "*";
  next j
  print

next i</lang>

Befunge

<lang befunge>1>:5`#@_:>"*",v

        | :-1<
^+1,+5+5<</lang>

Brainf***

This example is incomplete. Uneven brackets Please ensure that it meets all task requirements and remove this message.

<lang bf>>>+++++++[>++++++[>+<-]<-] place * in cell 3 +++++[>++[>>+<<-]<-]<< place \n in cell 4 +++++[ set outer loop count [>+ increment inner counter >[-]>[-]<<[->+>+<<]>>[-<<+>>]<< copy inner counter >[>>.<<-]>>>.<<< print line <<-] end loop</lang>

C

<lang c>int i, j; for (i = 1; i <= 5; i++) {

 for (j = 1; j <= i; j++)
   putchar('*');
 puts("");

}</lang>

C++

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

 for(int j = 1; j <= i; j++)
   std::cout << "*";
 std::cout << std::endl;

}</lang>

C#

<lang csharp>using System;

class Program {

   static void Main(string[] args)
   {
       for (int i = 0; i < 5; i++)
       {
           for (int j = 0; j <= i; j++)
           {
               Console.Write("*");
           }
           Console.WriteLine();
       }
   }

}</lang>

Clojure

<lang clojure>(doseq [i (range 5), j (range (inc i)]

 (print "*")
 (if (= i j) (println)))</lang>

ColdFusion

Remove the leading space from the line break tag.

With tags: <lang cfm><cfloop index = "i" from = "1" to = "5">

 <cfloop index = "j" from = "1" to = "#i#">
   *
 </cfloop>
 < br />

</cfloop></lang> With script: <lang cfm><cfscript>

 for( i = 1; i <= 5; i++ )
 {
   for( j = 1; j <= i; j++ )
   {
     writeOutput( "*" );
   }
   writeOutput( "< br />" );
 }

</cfscript></lang>

Common Lisp

<lang lisp>(loop for i from 1 upto 5 do

 (loop for j from 1 upto i do
   (write-char #\*))
 (write-line ""))</lang>

<lang lisp>(dotimes (i 5)

 (dotimes (j (+ i 1))
   (write-char #\*))
 (terpri))</lang>

<lang lisp>(do ((i 1 (+ i 1)))

   ((> i 5))
 (do ((j 1 (+ j 1)))
     ((> j i))
   (write-char #\*))
 (terpri))</lang>

D

<lang d>for(int i = 0; i < 5; i++) {

 for(int j = 0; j <= i; j++)
   writef("*") ;
 writefln() ;

}</lang> Foreach Range Statement since D2.003 <lang d>foreach(i ; 0..5) {

 foreach(j ; 0..i+1)
   writef("*") ;
 writefln() ;

}</lang>

Dao

<lang dao>for( i = 1 : 5 ){

   for( j = 1 : i ) io.write( '*' )
   io.writeln()

}</lang>

DMS

<lang DMS>number i, j for (i = 1; i <= 5; i++) {

   for (j = 1; j <= i; j++)
   {
       Result( "*" )
   }
   Result( "\n" )

}</lang>

E

<lang e>for width in 1..5 {

   for _ in 1..width {
       print("*")
   }
   println()

}</lang>

This loop is a combination of for ... in ... which iterates over something and a..b which is a range object that is iteratable. (Also, writing a..!b excludes the value b.)

FALSE

<lang false>1[$6-][$[$]["*"1-]#%" "1+]#%</lang>

Factor

<lang factor>5 [1,b] [ [ "*" write ] times nl ] each</lang>

Forth

<lang forth>: triangle ( n -- )

 1+ 1 do
   cr i 0 do [char] * emit loop
 loop ;

5 triangle</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran>DO i = 1, 5

 DO j = 1, i
   WRITE(*, "(A)", ADVANCE="NO") "*"
 END DO
 WRITE(*,*)

END DO</lang>

Fortran 95 (and later) has also a loop structure that can be used only when the result is independent from real order of execution of the loop.

Works with: Fortran version 95 and later

<lang fortran>integer :: i integer, dimension(10) :: v

forall (i=1:size(v)) v(i) = i</lang>

F#

<lang fsharp>#light [<EntryPoint>] let main args =

   for i = 1 to 5 do
       for j = 1 to i do
           printf "*"
       printfn ""
   0</lang>

Go

<lang go>for i := 1; i <= 5; i++ {

 for j := 1; j <= i; j++ {
   fmt.Printf("*")
 }
 fmt.Printf("\n")

}</lang>

HaXe

<lang HaXe>for (i in 1...6) { for(j in 0...i) { Lib.print('*'); } Lib.println(); }</lang>

Haskell

<lang haskell>import Control.Monad

main = do

 forM_ [1..5] $ \i -> do
   forM_ [1..i] $ \j -> do
     putChar '*'
   putChar '\n'</lang>

But it's more Haskellish to do this without loops:

<lang haskell>import Data.List (inits)

main = mapM_ putStrLn $ tail $ inits $ replicate 5 '*'</lang>

HicEst

<lang hicest>DO i = 1, 5

 DO j = 1, i
   WRITE(APPend) "*"
 ENDDO
 WRITE() ' '

ENDDO</lang>

J

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

  ]\ '*****'

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

       for_i. 1 + i. y do.
            z =. 
            for. 1 + i. i do.
                 z=. z,'*'
            end. 
            z 1!:2 ] 2 
        end.
       i.0 0
  )</lang>

But you would never see J code like this.

Java

<lang java>for (int i = 0; i < 5; i++) {

  for (int j = 0; j <= i; j++) {
     System.out.print("*");
  }
  System.out.println();

}</lang>

JavaScript

<lang javascript>for (var i=1; i<=5; i++) {

 s = "";
 for (var j=0; j<i; j++)
   s += '*';
 print(s);

}</lang>

Lua

<lang lua> for i=1,5 do

 for j=1,i do
   io.write("*")
 end
 io.write("\n")

end </lang>

Lisaac

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

 1.to i do { dummy : INTEGER;
   '*'.print;
 };
 '\n'.print;

};</lang>

<lang logo>for [i 1 5] [repeat :i [type "*] (print)] repeat 5 [repeat repcount [type "*] (print)]</lang>

M4

<lang M4>define(`for',

  `ifelse($#,0,``$0,
  `ifelse(eval($2<=$3),1,
  `pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl

for(`x',`1',`5',`1',

  `for(`y',`1',x,`1',
     `*')

')</lang>

Mathematica

<lang Mathematica>n=5; For[i=1,i<=5,i++,

string="";
For[j=1,j<=i,j++,string=string<>"*"];
Print[string]

]</lang>

MATLAB

<lang MATLAB>for i = (1:5)

   output = [];
   for j = (1:i)
       output = [output '*'];
   end
   
   disp(output);

end</lang>

MAXScript

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

   line = ""
   for j in 1 to i do
   (
       line += "*"
   )
   format "%\n" line

)</lang>

Modula-3

<lang modula3>MODULE Stars EXPORTS Main;

IMPORT IO;

BEGIN

 FOR i := 1 TO 5 DO
   FOR j := 1 TO i DO
     IO.Put("*");
   END;
   IO.Put("\n");
 END;

END Stars.</lang>

MOO

<lang moo>for i in [1..5]

 s = "";
 for j in [1..i]
   s += "*";
 endfor
 player:tell(s);

endfor</lang>

MUMPS

Routine

<lang MUMPS>FORLOOP

NEW I,J
FOR I=1:1:5 DO
.FOR J=1:1:I DO
..WRITE "*"
.WRITE !
QUIT</lang>

Output:

USER>D FORLOOP^ROSETTA
*
**
***
****
*****

One line

The if statement has to follow the write, or else the if statement would control the write (5 lines with one asterisk each). <lang MUMPS>FOR I=1:1:5 FOR J=1:1:I WRITE "*" IF J=I W !</lang>

NewLISP

<lang NewLISP> (for (i 1 5)

 (for(j 1 i)
   (print "*"))
 (print "\n"))

</lang>

Nimrod

<lang Python>for i in 1..5:

 for i in 1..i:
   stdout.write("*")
 echo("")</lang>

Objeck

<lang objeck> bundle Default {

 class For {
   function : Main(args : String[]), Nil {
     DoFor();
   }
   function : native : DoFor(), Nil {
   	for (i := 0; i < 5; i += 1;) {
         for (j := 0; j <= i; j += 1;) {
           "*"->Print();
         };
         ""->PrintLine();	
      };
   }
 }

} </lang>

OCaml

<lang ocaml>for i = 1 to 5 do

 for j = 1 to i do
   print_string "*"
 done;
 print_newline ()

done</lang>

Octave

<lang octave>for i = 0:1:4

 for j = 0:1:i
   printf("*");
 endfor
 printf("\n");

endfor</lang>

Oz

<lang oz>for I in 1..5 do

  for _ in 1..I do
     {System.printInfo "*"}
  end
  {System.showInfo ""}

end</lang> Note: we don't use the inner loop variable, so we prefer not to give it a name.

Pascal

<lang pascal>program stars(output);

var

 i, j: integer;

begin

 for i := 1 to 5 do
   begin
     for j := 1 to i do
       write('*');
     writeln
   end

end.</lang>

Perl

<lang perl>for ($x = 1; $x <= 5; $x++) {

 for ($y = 1; $y <= $x; $y++) {
   print "*";
 } 
 print "\n";

}</lang> <lang perl>foreach (1..5) {

 foreach (1..$_) {
   print '*';
 }
 print "\n";

}</lang>

However, if we lift the constraint of two loops the code will be simpler:

<lang perl>print ('*' x $_ . "\n") for 1..5</lang>

Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

<lang perl6>for ^5 {

for 0..$_ { print "*"; }

print "\n";

}</lang>

or using only one for loop:

<lang perl6>say '*' x $_ for 1..5;</lang>

or without using any loops at all:

<lang perl6>([\~] "*" xx 5).join("\n").say;</lang>

PHP

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

 for ($j = 1; $j <= $i; $j++) {
   echo '*';
 }
 echo "\n";

}</lang> or <lang php>foreach (range(1, 5) as $i) {

 foreach (range(1, $i) as $j) {
   echo '*';
 }
 echo "\n";

}</lang>

PicoLisp

<lang PicoLisp>(for N 5

  (do N (prin "*"))
  (prinl) )</lang>

Pike

<lang pike>int main(){

  for(int i = 1; i <= 5; i++){
     for(int j=1; j <= i; j++){
        write("*");
     }
     write("\n");
  }

}</lang>

PL/I

<lang PL/I> do i = 1 to 5;

  put skip edit (('*' do j = 1 to i)) (a);

end; </lang>

Pop11

<lang pop11>lvars i, j; for i from 1 to 5 do

   for j from 1 to i do
       printf('*','%p');
   endfor;
   printf('\n')

endfor;</lang>

PowerShell

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

   for ($j = 1; $j -le $i; $j++) {
       Write-Host -NoNewline *
   }
   Write-Host

}</lang> Alternatively the same can be achieved with a slightly different way by using the range operator along with the ForEach-Object cmdlet: <lang powershell>1..5 | ForEach-Object {

   1..$_ | ForEach-Object {
       Write-Host -NoNewline *
   }
   Write-Host

}</lang> while the inner loop wouldn't strictly be necessary and can be replaced with simply "*" * $_.

PureBasic

<lang PureBasic>If OpenConsole()

 Define i, j
 For i=1 To 5
   For j=1 To i
     Print("*")
   Next j
   PrintN("")
 Next i
 Print(#LFCR$+"Press ENTER to quit"): Input()
 CloseConsole()

EndIf</lang>

Python

<lang python>import sys for i in xrange(5):

   for j in xrange(i+1):
       sys.stdout.write("*")
   print</lang>

Note that we have a constraint to use two for loops, which leads to non-idiomatic Python. If that constraint is dropped we can use the following, more idiomatic Python solution: <lang python>for i in range(1,6):

   print '*' * i</lang>

R

<lang R>for(i in 0:4) {

 s <- ""
 for(j in 0:i) {
   s <- paste(s, "*", sep="")
 }
 print(s)

}</lang>

REBOL

<lang REBOL>; Use 'repeat' when an index required, 'loop' when repetition suffices:

repeat i 5 [ loop i [prin "*"] print "" ]

or a more traditional for loop

for i 1 5 1 [ loop i [prin "*"] print "" ]</lang>


REXX

<lang rexx>do i = 1 to 5

 s = 
 do j = 1 to i
   s = s || '*'
 end
 say s

end</lang>

Ruby

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

  for j in 1..i do
     print "*"
  end
  puts ""

end</lang> or <lang ruby>1.upto(5) do |i|

  1.upto(i) do |j|
     print "*"
  end
  puts ""

end</lang> or <lang ruby>5.times do |i| # i goes from 0 to 4

  (i+1).times do
     print "*"
  end
  puts ""

end</lang>

Sather

Sather allows the definition of new iterators. Here's we define for! so that it resembles the known for in other languages, even though the upto! built-in can be used.

<lang sather>class MAIN is

 -- from, to, step
 for!(once init:INT, once to:INT, once inc:INT):INT is
   i ::= init;
   loop while!( i <= to );
     yield i;
     i := i + inc;
   end;
 end;
 main is
   i, j :INT;
   loop i := for!(1, 5, 1);   -- 1.upto!(5)
     loop j := for!(1, i, 1); -- 1.upto!(i)
       #OUT + "*";
     end;
     #OUT + "\n";
   end;
 end;

end; </lang>

Scheme

<lang scheme>(do ((i 1 (+ i 1)))

   ((> i 5))
   (do ((j 1 (+ j 1)))
       ((> j i))
       (display "*"))
   (newline))</lang>

Seed7

<lang seed7>for I range 1 to 5 do

 for J range 1 to I do
   write("*");
 end for;
 writeln;

end for;</lang>

Slate

<lang slate>1 to: 5 do: [| :n | inform: ($* repeatedTimes: n)].</lang>

Scala

<lang scala>for (i <- 1 to 5) {

   for (j <- 1 to i)
       print("*")
   println

}</lang>

Smalltalk

<lang smalltalk>1 to: 5 do: [ :aNumber |

 aNumber timesRepeat: [ '*' display ].
 Character nl display.

]</lang>

SNOBOL4

A slightly longer, "mundane" version

<lang snobol>ol outer = ?lt(outer,5) outer + 1 :f(end) inner = outer; stars = "" il stars = ?gt(inner,0) stars "*" :f(disp) inner = inner - 1 :(il) disp output = stars; :(ol) end</lang>

The "real SNOBOL4" starts here: <lang snobol>outer b = a = ?lt(a,5) a + 1 :f(end) inner t = t ?(b = (gt(b,0) b - 1)) "*" :s(inner) t span("*") . terminal = :(outer) end</lang>

one "loop" only: <lang snobol> a = "*****"; a a len(x = x + 1) . output :s(a) end</lang>

... or just (courtesy of GEP2):

Works with: SNOBOL4 version which defaults to anchored mode

<lang snobol> "*****" arb $ output fail end</lang>

Suneido

<lang Suneido>for(i = 0; i < 5; ++i)

   {
   str = 
   for (j = 0; j <= i; ++j)
       str $= '*'
   Print(str)
   }</lang>

Tcl

<lang tcl>for {set lines 1} {$lines <= 5} {incr lines} {

   for {set i 1} {$i <= $lines} {incr i} {
       puts -nonewline *
   }
   puts ""

}</lang> Note that it would be more normal to produce this output with: <lang tcl>for {set i 1} {$i <= 5} {incr i} {

   puts [string repeat "*" $i]

}</lang>

It bears noting that the three parts of the for loop do not have to consist of "initialize variable", "test value of variable" and "increment variable". This is a common way to think of it as it resembles the "for" loop in other languages, but many other things make sense. For example this for-loop will read a file line-by-line:

<lang tcl>set line "" for { set io [open test.txt r] } { ![eof $io] } { gets $io line } {

   if { $line != "" } { ...do something here... }

}</lang>

(This is a somewhat awkward example; just to show what is possible)

TI-89 BASIC

<lang ti89b>Local i,j ClrIO For i, 1, 5

 For j, 1, i
   Output i*8, j*6, "*"
 EndFor

EndFor</lang>

UNIX Shell

Works with: Bourne Again SHell version 3

<lang bash>for (( x=1; $x<=5; x=$x+1 )); do

 for (( y=1; y<=$x; y=$y+1 )); do 
   echo -n '*'
 done
 echo ""

done</lang>

UnixPipes

<lang bash>yes \ | cat -n | (while read n ; do

 [ $n -gt 5 ] && exit 0;
 yes \* | head -n $n | xargs -n $n echo

done)</lang>

Vedit macro language

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

   for (#2 = 1; #2 <= #1; #2++) {
       Type_Char('*')
   }
   Type_Newline

}</lang>

Visual Basic

<lang vb>'This Prints to the Debug-Window! Dim i As Integer Dim ii As Integer Dim x As Integer Dim output As String

output = ""

For i = 1 To 5

   For ii = 1 To i
       output = output + "*"
   Next ii
   Debug.Print (output)
   output = ""

Next i</lang>

Visual Basic .NET

Works with: Visual Basic version 2002

<lang vbnet>For x As Integer = 0 To 4

   For y As Integer = 0 To x
       Console.Write("*")
   Next
   Console.WriteLine()

Next</lang>