Loops/For

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

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

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:

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

Contents

[edit] ActionScript

var str:String = "";
for (var i:int = 1; i <= 5; i++) {
for (var j:int = 1; j <= i; j++)
str += "*";
trace(str);
str = "";
}

[edit] Ada

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

[edit] ALGOL 60

FOR i:=1 UNTIL 5 DO
FOR j:=1 UNTIL i DO
OUTTEXT("*");
OUTLINE

[edit] 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
FOR i TO 5 DO
TO i DO
print("*")
OD;
print(new line)
OD
Output:
*
**
***
****
*****

[edit] Alore

for i in 0 to 6
for j in 0 to i
Write('*')
end
WriteLn()
end
 

[edit] AmigaE

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

[edit] 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
Output:
"

"

[edit] 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

[edit] AWK

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

[edit] Babel

((main { 10 star_triangle ! })
 
(star_triangle {
dup
<-
{ dup { "*" << } <->
iter - 1 +
times
"\n" << }
->
times }))
Output:
*
**
***
****
*****
******
*******
********
*********
**********

The key operator here is 'iter' which gives the current iteration of the loop body it resides in. When used with the 'times' operator, it generates a countdown.


[edit] bash

 
for i in {1..5}
do
for ((j=1; j<=i; j++));
do
echo -n "*"
done
echo
done
 


[edit] BASIC

Works with: QuickBasic version 4.5
FOR i = 1 TO 5
FOR j = 1 TO i
PRINT "*";
NEXT j
PRINT
NEXT i

[edit] Applesoft BASIC

FOR I = 1 TO 5 : FOR J = 1 TO I : PRINT "*"; : NEXT J : PRINT : NEXT

[edit] BBC BASIC

 
FOR I% = 1 TO 5
FOR J% = 1 TO I%
PRINT"*";
NEXT
PRINT
NEXT
 

[edit] Creative Basic

 
OPENCONSOLE
 
FOR X=1 TO 5
 
FOR Y=1 TO X
 
PRINT"*",:'No line feed or carriage return after printing.
 
NEXT Y
 
PRINT
 
NEXT X
 
PRINT:PRINT"Press any key to end."
 
DO:UNTIL INKEY$<>""
 
CLOSECONSOLE
 
END
 

[edit] GW-BASIC

10 FOR I = 1 TO 5
20 FOR J = 1 TO I
30 PRINT "*";
40 NEXT J
50 PRINT
60 NEXT I
 

[edit] FBSL

 
#APPTYPE CONSOLE
FOR DIM i = 1 TO 5
FOR DIM j = 1 TO i
PRINT "*";
NEXT j
PRINT
NEXT i
Pause
Output:
*
**
***
****
*****
Press any key to continue...

[edit] IWBASIC

 
OPENCONSOLE
 
FOR X=1 TO 5
 
FOR Y=1 TO X
 
LOCATE X,Y:PRINT"*"
 
NEXT Y
 
NEXT X
 
PRINT
 
CLOSECONSOLE
 
END
 
'Could also have been written the same way as the Creative Basic example, with no LOCATE command.
 

[edit] Liberty BASIC

Unlike some BASICs, Liberty BASIC does not require that the counter variable be specified with 'next'.

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

[edit] 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

[edit] Run BASIC

 
FOR i = 1 TO 5
FOR j = 1 TO i
PRINT "*";
NEXT j
PRINT
NEXT i
 

[edit] Visual Basic

Works with: VB6

Public OutConsole As Scripting.TextStream
For i = 0 To 4
For j = 0 To i
OutConsole.Write "*"
Next j
OutConsole.WriteLine
Next i

[edit] Visual Basic .NET

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

[edit] ZX Spectrum Basic

On the ZX Spectrum, we need line numbers:

 
10 FOR i = 1 TO 5
20 FOR j = 1 TO i
30 PRINT "*";
40 NEXT j
50 PRINT
60 NEXT i
 

[edit] Batch File

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
 
for /l %%i in (1,1,5) do (
SET line=
for /l %%j in (1,1,%%i) do (
SET line=!line!*
)
ECHO !line!
)
 
ENDLOCAL

[edit] bc

for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++) "*"
"
"
}
quit

[edit] Befunge

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

[edit] Bracmat

  0:?i
& whl
' ( !i+1:~>5:?i
& 0:?k
& whl'(!k+1:~>!i:?k&put$"*")
& put$\n
)
&
);

[edit] Brainf***

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

[edit] Brat

1.to 5, { i |
1.to i, { j |
print "*"
}
print "\n"
}

[edit] C

int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++)
putchar('*');
puts("");
}

[edit] C++

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

[edit] C#

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

[edit] Chapel

for i in 1..5 {
for 1..i do write('*');
writeln();
}

[edit] Chef

Asterisks Omelette.
 
This recipe prints a triangle of asterisks.
 
Ingredients.
5 eggs
1 onion
1 potato
42 ml water
10 ml olive oil
1 garlic
 
Method.
Put eggs into the mixing bowl.
Fold onion into the mixing bowl.
Put eggs into the mixing bowl.
Add garlic into the mixing bowl.
Fold eggs into the mixing bowl.
Chop onion.
Put onion into the mixing bowl.
Fold potato into the mixing bowl.
Put olive oil into the mixing bowl.
Mash potato.
Put water into the mixing bowl.
Mash potato until mashed.
Chop onion until choped.
Pour contents of the mixing bowl into the baking dish.
 
Serves 1.

[edit] COBOL

       IDENTIFICATION DIVISION.
PROGRAM-ID. Display-Triangle.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Outer-Counter PIC 9.
01 Inner-Counter PIC 9.
 
PROCEDURE DIVISION.
PERFORM VARYING Outer-Counter FROM 1 BY 1 UNTIL 5 < Outer-Counter
 
PERFORM VARYING Inner-Counter FROM 1 BY 1
UNTIL Outer-Counter < Inner-Counter
DISPLAY "*" NO ADVANCING
END-PERFORM
 
DISPLAY "" *> Output a newline
END-PERFORM
 
GOBACK
.
 

[edit] Coq

Section FOR.
Variable T : Type.
Variable body : nat -> T -> T.
Variable start : nat.
 
Fixpoint for_loop n : T -> T :=
match n with
| O => fun s => s
| S n' => fun s => for_loop n' (body (start + n') s)
end.
 
End FOR.
 
Eval vm_compute in
for_loop _
(fun i =>
cons
(for_loop _
(fun j => cons tt)
0 (S i) nil
)
)
0 5 nil.
 

[edit] Clojure

(doseq [i (range 5), j (range (inc i))]
(print "*")
(if (= i j) (println)))

[edit] 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>

[edit] Common Lisp

(loop for i from 1 upto 5 do
(loop for j from 1 upto i do
(write-char #\*))
(write-line ""))
(dotimes (i 5)
(dotimes (j (+ i 1))
(write-char #\*))
(terpri))
(do ((i 1 (+ i 1)))
((> i 5))
(do ((j 1 (+ j 1)))
((> j i))
(write-char #\*))
(terpri))

[edit] D

import std.stdio: write, writeln;
 
void main() {
for (int i; i < 5; i++) {
for (int j; j <= i; j++)
write("*");
writeln();
}
writeln();
 
foreach (i; 0 .. 5) {
foreach (j; 0 .. i + 1)
write("*");
writeln();
}
}
Output:
*
**
***
****
*****

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

[edit] Dao

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

[edit] Dart

main() {
for (var i = 0; i < 5; i++)
for (var j = 0; j < i + 1; j++)
print("*");
print("\n");
}

[edit] dc

[...]sA defines the inner loop A and [...]sB defines the outer loop B. This program nests the entrance to loop A inside loop B.

Translation of: bc
[
[*]P [print asterisk]sz
lj 1 + d sj [increment j, leave it on stack]sz
li !<A [continue loop if i >= j]sz
]sA
[
1 d sj [j = 1, leave it on stack]sz
li !<A [enter loop A if i >= j]sz
[
]P [print newline]sz
li 1 + d si [increment i, leave it on stack]sz
5 !<B [continue loop if 5 >= i]sz
]sB
1 d si [i = 1, leave it on stack]sz
5 !<B [enter loop B if 5 >= i]sz

[edit] Delphi

program LoopFor;
 
{$APPTYPE CONSOLE}
 
var
i, j: Integer;
begin
for i := 1 to 5 do
begin
for j := 1 to i do
Write('*');
Writeln;
end;
end.

[edit] DWScript

var i, j : Integer;
 
for i := 1 to 5 do begin
for j := 1 to i do
Print('*');
PrintLn('');
end;

[edit] dodo0

fun for -> var, test, body, return    # define a for loop using recursion
(
test(var) -> continue
if (continue) ->
(
body(var) -> var
for (var, test, body, return)
)
|
return(var)
)
| for
 
fun upToFive (-> index, return) '<='(index, 5, return) | upToFive
 
for (1, upToFive) -> index, return
(
fun countTheStars -> stars, return
(
'count'(stars) -> n
'<'(n, index, return) # continue until n = index
)
| countTheStars
 
for ("*", countTheStars) -> prefix, return
'str'(prefix, "*", return)
| stars
 
println(stars) ->
 
'inc'(index, return)
)
| result
exit()

[edit] DMS

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

[edit] E

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

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

[edit] Ela

open console
 
loop m n | n < m = loop' n 0 $ writen "" $ loop m (n+1)
| else = ()
where loop' m n | n <= m = write "*" $ loop' m (n+1)
| else = ()

[edit] EGL

str string;
for ( i int to 5 )
str = "";
for ( j int to i )
str += "*";
end
SysLib.writeStdout(str);
end


[edit] Erlang

%% Implemented by Arjun Sunel
-module(nested_loops).
-export([main/0, inner_loop/0]).
 
main() ->
outer_loop(1).
 
inner_loop()->
inner_loop(1).
 
inner_loop(N) when N rem 5 =:= 0 ->
io:format("* ");
 
inner_loop(N) ->
io:fwrite("* "),
inner_loop(N+1).
 
outer_loop(N) when N rem 5 =:= 0 ->
io:format("*");
 
outer_loop(N) ->
outer_loop(N+1),
io:format("~n"),
inner_loop(N).
 


[edit] ERRE

 
FOR I=1 TO 5 DO
FOR J=1 TO I DO
PRINT("*";)
END FOR
PRINT
END FOR
 

[edit] Euphoria

 
for i = 1 to 5 do
for j = 1 to i do
puts(1, "*") -- Same as "puts(1, {'*'})"
end for
puts(1, "\n") -- Same as "puts(1, {'\n'})"
end for
 

puts() is a function that takes two arguments; an integer and a sequence. Strings are simply sequences; there is no string type. The integer specifies where to put the "string". 0 = STDIN, 1 = STDOUT, 2 = STDERR, 3+ = files that are opened with the open() function. puts() prints the sequence out, as a "string". Each element in the sequence provided is printed out as the character with that value in the ASCII character chart.

[edit] FALSE

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

[edit] Factor

5 [1,b] [ [ "*" write ] times nl ] each

[edit] Fantom

Using for loops:

 
class ForLoops
{
public static Void main ()
{
for (Int i := 1; i <= 5; ++i)
{
for (Int j := 1; j <= i; ++j)
{
Env.cur.out.print ("*")
}
Env.cur.out.printLine ("")
}
}
}
 

Using range objects:

 
class ForLoops
{
public static Void main ()
{
(1..5).each |i|
{
(1..i).each |j|
{
Env.cur.out.print ("*")
}
Env.cur.out.printLine ("")
}
}
}
 

[edit] Forth

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

One more:

 
: limit_example
15 1 do r> r@ dup rot >r drop \ Bring limit on stack
. \ And print it
loop ;
\ Gforth and JSForth all work, SP-Forth brakes (different 'for' implementation?)
 

[edit] Fortran

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.
PROGRAM FORLOOP
INTEGER I, J
 
DO 20 I = 1, 5
DO 10 J = 1, I
C Print the asterisk.
WRITE (*,5001) '*'
10 CONTINUE
C Print a newline.
WRITE (*,5000) ''
20 CONTINUE
 
STOP
 
5000 FORMAT (A)
C Standard FORTRAN 77 is completely incapable of completing a
C WRITE statement without printing a newline. If you wanted to
C write this program in valid F77, you would have to come up with
C a creative way of printing varying numbers of asterisks in a
C single write statement.
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 (A, $)
C5001 FORMAT (A, ADVANCE='NO')
END
Works with: Fortran version 90 and later
DO i = 1, 5
DO j = 1, i
WRITE(*, "(A)", ADVANCE="NO") "*"
END DO
WRITE(*,*)
END DO

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
integer :: i
integer, dimension(10) :: v
 
forall (i=1:size(v)) v(i) = i

[edit] Frink

 
for n = 1 to 5
{
for a = 1 to n
print["*"]
 
println[]
}
 

[edit] F#

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

[edit] Gambas

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

[edit] GAP

for i in [1 .. 5] do
for j in [1 .. i] do
Print("*");
od;
Print("\n");
od;
 
# *
# **
# ***
# ****
# *****

[edit] GML

pattern = ""
for(i = 1; i <= 5; i += 1)
{
for(j = 1; j <= i; j += 1)
{
pattern += "*"
}
pattern += "#"
}
show_message(pattern)

[edit] Go

package main
 
import "fmt"
 
func main() {
for i := 1; i <= 5; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("*")
}
fmt.Printf("\n")
}
}
Output:
*
**
***
****
*****

[edit] Groovy

Solution:

for(i in (1..6)) {
for(j in (1..i)) {
print '*'
}
println ()
}

[edit] Haxe

for (i in 1...6) {
for(j in 0...i) {
Sys.print('*');
}
Sys.println('');
}

[edit] Haskell

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

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

import Data.List (inits)
 
main = mapM_ putStrLn $ tail $ inits $ replicate 5 '*'

[edit] HicEst

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

[edit] Icon and Unicon

[edit] Icon

procedure main()
every i := 1 to 5 do {
every 1 to i do
writes("*")
write()
}
end

[edit] Unicon

The Icon solution works in Unicon.

[edit] Inform 7

repeat with length running from 1 to 5:
repeat with N running from 1 to length:
say "*";
say line break;

[edit] J

J is array-oriented, so there is very little need for loops. For example, except for the requirement for loops, 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 almost never see J code like this.

[edit] Java

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

[edit] JavaScript

var i, j;
for (i = 1; i <= 5; i += 1) {
s = '';
for (j = 0; j < i; j += 1)
s += '*';
document.write(s + '<br>');
}

[edit] jq

# Single-string version using explicit nested loops:
def demo(m):
reduce range(0;m) as $i
(""; reduce range(0;$i) as $j
(.; . + "*" ) + "\n" ) ;
 
# Stream of strings:
def demo2(m):
range(1;m)
| reduce range(0;.) as $j (""; . + "*");
 
# Variation of demo2 using an implicit inner loop:
def demo3(m): range(1;m) | "*" * . ;

Example using demo(6)

Output:
$ jq -r -n -f loops_for.jq
*
**
***
****
*****

[edit] LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
LabVIEW Loops For.png

[edit] Lang5

: cr  "\n" . ;      : dip  swap '_ set execute _ ;
: nip swap drop ;  : last -1 extract nip ;
: times
swap iota '_ set
do dup 'execute dip _ last 0 == if break then
loop drop ;
 
: concat "" join ;
'* 1 5 "2dup reshape concat . cr 1 +" times


[edit] Lasso

loop(5) => {^
loop(loop_count) => {^ '*' ^}
'\r'
^}

[edit] Lisaac

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

[edit]

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

[edit] Lua

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

[edit] 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',
`*')
')

[edit] make

Works with: BSD make
Library: jot
all: line-5
 
ILIST != jot 5
.for I in $(ILIST)
 
line-$(I): asterisk-$(I)-$(I)
@echo
 
JLIST != jot $(I)
. for J in $(JLIST)
 
. if "$(J)" == "1"
. if "$(I)" == "1"
asterisk-1-1:
. else
IM != expr $(I) - 1
asterisk-$(I)-1: line-$(IM)
. endif
. else
JM != expr $(J) - 1
asterisk-$(I)-$(J): asterisk-$(I)-$(JM)
. endif
@printf \*
 
. endfor
.endfor

[edit] Maple

> for i to 5 do to i do printf( "*" ) end; printf( "\n" ) end;
*
**
***
****
*****


[edit] Mathematica

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

[edit] MATLAB / Octave

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

Vectorized version:

for i = (1:5)
disp(repmat('*',1,i));
end

[edit] Maxima

for i thru 5 do (
s: "",
thru i do s: sconcat(s, "*"),
print(s)
);

[edit] MAXScript

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

[edit] Mercury

:- module loops_for.
:- interface.
 
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
:- import_module int.
 
main(!IO) :-
int.fold_up(outer_loop_body, 1, 5, !IO).
 
:- pred outer_loop_body(int::in, io::di, io::uo) is det.
 
outer_loop_body(I, !IO) :-
int.fold_up(inner_loop_body, 1, I, !IO),
io.nl(!IO).
 
:- pred inner_loop_body(int::in, io::di, io::uo) is det.
 
inner_loop_body(_, !IO) :-
io.write_char('*', !IO).

[edit] Modula-2

MODULE For;
IMPORT InOut;
 
VAR
i, j: INTEGER;
 
BEGIN
FOR i := 1 TO 5 DO
FOR j := 1 TO i DO
InOut.Write('*');
END;
InOut.WriteLn
END
END For.

[edit] Modula-3

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.

[edit] MOO

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

[edit] MUMPS

[edit] Routine

FORLOOP
NEW I,J
FOR I=1:1:5 DO
.FOR J=1:1:I DO
..WRITE "*"
.WRITE !
QUIT
Output:
USER>D FORLOOP^ROSETTA
*
**
***
****
*****

[edit] 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).

FOR I=1:1:5 FOR J=1:1:I WRITE "*" IF J=I W !

[edit] Nemerle

for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
Write("*");
}
WriteLine();
}

[edit] NetRexx

/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
say
say 'Loops/For'
 
loop i_ = 1 to 5
loop for i_
say '*\-'
end
say
end i_
 

[edit] NewLISP

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

[edit] Nimrod

for i in 1..5:
for i in 1..i:
stdout.write("*")
echo("")

[edit] 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();
};
}
}
}
 

[edit] OCaml

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

[edit] Octave

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

[edit] Order

#include <order/interpreter.h>
 
ORDER_PP(
8for_each_in_range(8fn(8I,
8print(
8for_each_in_range(8fn(8J, 8print((*))),
1, 8plus(8I, 1))
8space)),
1, 6)
)

(Order cannot print newlines, so this example just uses a space.)

[edit] Oz

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

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

[edit] Panoramic

 
dim x,y
 
for x=1 to 5
 
for y=1 to x
 
print "*";
 
next y
 
print
 
next x
 

[edit] PARI/GP

for(a=1,5,for(b=1,a,print1("*"));print())

[edit] 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.

[edit] Perl

for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= $x; $y++) {
print "*";
}
print "\n";
}
foreach (1..5) {
foreach (1..$_) {
print '*';
}
print "\n";
}

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

print ('*' x $_ . "\n") for 1..5

[edit] Perl 6

Works with: Rakudo version #22 "Thousand Oaks"
for ^5 {
 
for 0..$_ {
print "*";
}
 
print "\n";
 
}

or using only one for loop:

say '*' x $_ for 1..5;

or without using any loops at all:

([\~] "*" xx 5).join("\n").say;

[edit] PHP

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

or

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

[edit] PicoLisp

(for N 5
(do N (prin "*"))
(prinl) )

[edit] Pike

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

[edit] PL/I

Basic version:

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

Advanced version:

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

Due to the new line requirement a mono line version is not possible

put edit ((('*' do j = 1 to i)do i=1 to 5))(a);  /* no new line */

[edit] Pop11

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

[edit] PowerShell

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

Alternatively the same can be achieved with a slightly different way by using the range operator along with the ForEach-Object cmdlet:

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

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

[edit] Python

import sys
for i in xrange(5):
for j in xrange(i+1):
sys.stdout.write("*")
print

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:

for i in range(1,6):
print '*' * i

[edit] R

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

[edit] Racket

(for ([i (in-range 1 6)]) (for ([j i]) (display "*")) (newline))

[edit] 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 ""
]


[edit] REXX

[edit] version 1

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

[edit] version 2

  do i=1 for 5
s=''
do i
s=s'*'
end
say s
end

[edit] Retro

6 [ 0; cr [ '* emit ] times ] iter

[edit] Ruby

One can write a for loop as for i in 1..5; ...end or as for i in 1..5 do ... end or as (1..5).each do |i| ... end. All three forms call Range#each to iterate 1..5.

for Range#each
for i in 1..5
for j in 1..i
print "*"
end
puts
end
(1..5).each do |i|
(1..i).each do |j|
print "*"
end
puts
end

Ruby has other ways to code these loops; Integer#upto is most convenient.

Integer#upto Integer#times Kernel#loop
1.upto(5) do |i|
1.upto(i) do |j|
print "*"
end
puts
end
5.times do |i|
# i goes from 0 to 4
(i+1).times do
print "*"
end
puts
end
i = 1
loop do
j = 1
loop do
print "*"
break if (j += 1) > i
end
puts
break if (i += 1) > 5
end

Or we can use String#* as the inner loop, and Enumerable#map as the outer loop. This shrinks the program to one line.

puts (1..5).map { |i| "*" * i }

[edit] Salmon

iterate (x; [0...4])
{
iterate (y; [0...x])
print("*");;
print("\n");
};

or

for (x; 0; x < 5)
{
for (y; 0; y <= x)
print("*");;
print("\n");
};


[edit] SAS

data _null_;
length a $5;
do n=1 to 5;
a="*";
do i=2 to n;
a=trim(a) !! "*";
end;
put a;
end;
run;

[edit] 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.

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;
 

[edit] Scheme

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

[edit] Seed7

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

[edit] Sidef

for(;;) loop:

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

for([]) loop:

for (1..5) { |i|
for (1..i) { print '*' };
print "\n";
}

Alternatively:

for (1..5) { |i|
for (i..5) { |j|
say '*'*j; break;
}
}

[edit] Slate

1 to: 5 do: [| :n | inform: ($* repeatedTimes: n)].

[edit] Scala

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

[edit] Simula

Works with: SIMULA-67
FOR I:=1 UNTIL 5 DO
FOR J:=1 UNTIL I DO
OUTTEXT("*");
OUTLINE

[edit] Smalltalk

1 to: 5 do: [ :aNumber |
aNumber timesRepeat: [ '*' display ].
Character nl display.
]

or:

1 to: 5 do: [ :row |
1 to: row do: [:col | '*' display ].
]

(only for demonstration of nested for-loops; as the column is not needed, the first solution is probably clearer).

However, streams already have some builtin repetition mechanism, so a programmer might write:

Works with: Smalltalk/X
1 to: 5 do: [ :n |
Stdout next: n put: $*; cr
]

[edit] SNOBOL4

A slightly longer, "mundane" version

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

The "real SNOBOL4" starts here:

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

one "loop" only:

	a = "*****"; 
a a len(x = x + 1) . output :s(a)
end

... or just (courtesy of GEP2):

Works with: SNOBOL4 version which defaults to anchored mode
        "*****" arb $ output fail
end

[edit] Sparkling

for (var row = 1; row <= 5; row++) {
for (var col = 1; col <= row; col++) {
printf("*");
}
 
print();
}

[edit] Suneido

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

[edit] Swift

for i in 1...5 {
for j in 1...i {
print("*")
}
println()
}
Output:
*
**
***
****
*****

Alternately:

for i in 1..<6 {
for j in 1..<i+1 {
print("*")
}
println()
}
Output:
*
**
***
****
*****

Alternately:

for var i = 1; i <= 5; i++ {
for var j = 1; j <= i; j++ {
print("*")
}
println()
}
Output:
*
**
***
****
*****

[edit] Tcl

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

Note that it would be more normal to produce this output with:

for {set i 1} {$i <= 5} {incr i} {
puts [string repeat "*" $i]
}

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:

set line ""
for { set io [open test.txt r] } { ![eof $io] } { gets $io line } {
if { $line != "" } { ...do something here... }
}

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

[edit] TI-83 BASIC

For loops in TI-83 BASIC are notated with 3 or 4 parameters: For(A,B,C,D).
A is a the variable name to iterate
B is the number at which A starts
C is the number at which A stops (the for loop passes through once when A=B
D is optional, it is the increment value of A.

ClrHome
For(I,1,5)
For(J,1,I)
Output(I,J,"*")
End
End

[edit] TI-89 BASIC

Local i,j
ClrIO
For i, 1, 5
For j, 1, i
Output i*8, j*6, "*"
EndFor
EndFor

[edit] TorqueScript

for(%i = 0; %i < 5; %i++)
{
for(%x = %i; %x < 5; %x++)
{
 %string = %string @ "*";
echo(%string);
}
}

[edit] TUSCRIPT

 
$$ MODE TUSCRIPT
m=""
LOOP n=1,5
m=APPEND (m,"","*")
PRINT m
ENDLOOP
 
Output:
*
**
***
****
***** 

[edit] UNIX Shell

A conditional loop, using a while control construct, can have the same effect as a for loop. (The original Bourne Shell has no echo -n "*", so this uses printf "*".)

Works with: Bourne Shell
#!/bin/sh
# Using a while control construct to emulate a for loop
 
l="1" # Set the counters to one
while [ "$l" -le 5 ] # Loop while the counter is less than five
do
m="1"
while [ "$m" -le "$l" ] # Loop while the counter is less than five
do
printf "*"
m=`expr "$m" + 1` # Increment the inner counter
done
echo
l=`expr "$l" + 1` # Increment the outer counter
done

The Bourne Shell has a for loop, but it requires a list of words to iterate. The jot(1) command from BSD can output an appropriate list of numbers.

Works with: Bourne Shell
Library: jot
for i in `jot 5`; do
for j in `jot $i`; do
printf \*
done
echo
done

Bash has for loops that act like C. These loops are very good for this task.

Works with: Bourne Again SHell version 3
for (( x=1; $x<=5; x=$x+1 )); do 
for (( y=1; y<=$x; y=$y+1 )); do
echo -n '*'
done
echo ""
done

[edit] C Shell

Library: jot
foreach i (`jot 5`)
foreach j (`jot $i`)
echo -n \*
end
echo ""
end

[edit] UnixPipes

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

[edit] Vedit macro language

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

[edit] Wart

for i 1 (i <= 5) ++i
for j 0 (j < i) ++j
pr "*"
(prn)

[edit] XPL0

code ChOut=8, CrLf=9;
int I, J;
for I:= 1 to 5 do
[for J:= 1 to I do
ChOut(0, ^*);
CrLf(0);
]

[edit] zkl

foreach i in ([1..5]){
foreach j in (i){print("*")}
println();
}
Output:
*
**
***
****
*****
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox