Loops/For: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 402: Line 402:
puts ""
puts ""
end</lang>
end</lang>
or {{works with|Ruby|1.8.7+}}
or
<lang ruby>5.times do |i| # i goes from 0 to 4
<lang ruby>5.times do |i| # i goes from 0 to 4
(i+1).times do
(i+1).times do

Revision as of 01:10, 11 June 2009

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

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 Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
FOR i TO 5 DO
   TO i DO
      print("*")
   OD;
  print(new line)
OD

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>

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 autoexcution 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

1>:5`#@_:>"*",v
         | :-1<
 ^+1,+5+5<

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>

ColdFusion

Remove the leading space from the line break tag.

With tags:

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

With script:

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

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>

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

1[$6-][$[$]["*"1-]#%"
"1+]#%

Forth

: triangle ( n -- )
  1+ 1 do
    cr i 0 do [char] * emit loop
  loop ;
5 triangle

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#

#light
[<EntryPoint>]
let main args =
    for i = 1 to 5 do
        for j = 1 to i do
            printf "*"
        printfn ""
    0

Haskell

import Control.Monad

main = do
  forM_ [1..5] $ \i -> do
    forM_ [1..i] $ \j -> do
      putChar '*'
    putChar '\n'

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

   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
   )

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

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

for [i 1 5] [repeat :i [type "*] (print)]
repeat 5 [repeat repcount [type "*] (print)]

MAXScript

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

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>

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>

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

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>

Pop11

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

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>

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

Works with: Ruby version 1.8.7+

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

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

end</lang>

Scheme

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

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

Slate

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

Smalltalk

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

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

]</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>

UnixPipes

yes \ | cat -n | (while read n ; do
  [ $n -gt 5 ] && exit 0;
  yes \* | head -n $n | xargs -n $n echo
done)

Visual Basic .NET

Works with: Visual Basic version 2002
       For x As Integer = 0 To 4
           For y As Integer = 0 To x
               Console.Write("*")
           Next
           Console.WriteLine()
       Next