Loops/For: Difference between revisions
Added Quackery. |
Add SmallBASIC |
||
(81 intermediate revisions by 47 users not shown) | |||
Line 45: | Line 45: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">L(i) 1..5 |
||
L 1..i |
L 1..i |
||
print(‘*’, end' ‘’) |
print(‘*’, end' ‘’) |
||
print()</ |
print()</syntaxhighlight> |
||
Pythonic solution: |
Pythonic solution: |
||
< |
<syntaxhighlight lang="11l">L(i) 1..5 |
||
print(‘*’ * i)</ |
print(‘*’ * i)</syntaxhighlight> |
||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
;Basic - Algol style |
;Basic - Algol style |
||
The opcode BXH uses 3 registers, one for index, one for step and one for limit. |
The opcode BXH uses 3 registers, one for index, one for step and one for limit. |
||
< |
<syntaxhighlight lang="360asm"> |
||
* Loops/For - BXH Algol 27/07/2015 |
* Loops/For - BXH Algol 27/07/2015 |
||
LOOPFOR CSECT |
LOOPFOR CSECT |
||
Line 80: | Line 80: | ||
YREGS |
YREGS |
||
END LOOPFOR |
END LOOPFOR |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 91: | Line 91: | ||
;Structured Macros |
;Structured Macros |
||
Structured and without BXH, only one register used by loop. |
Structured and without BXH, only one register used by loop. |
||
< |
<syntaxhighlight lang="360asm"> |
||
* Loops/For - struct 29/06/2016 |
* Loops/For - struct 29/06/2016 |
||
LOOPFOR CSECT |
LOOPFOR CSECT |
||
Line 112: | Line 112: | ||
YREGS |
YREGS |
||
END LOOPFOR |
END LOOPFOR |
||
</ |
</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Same as above |
Same as above |
||
=={{header|68000 Assembly}}== |
|||
Although it's more natural for the language to loop downward rather than forward, both are possible. |
|||
<syntaxhighlight lang="68000devpac">main: |
|||
MOVEQ #1,D1 ;counter for how many times to print *, this is also the loop counter |
|||
.outerloop: |
|||
MOVE.W D1,D2 |
|||
SUBQ.W #1,D2 |
|||
.innerloop: |
|||
MOVE.B #'*',D0 |
|||
JSR PrintChar ;hardware-dependent printing routine |
|||
DBRA D2,.innerloop ;DBRA loops until wraparound to $FFFF, which is why we subtracted 1 from D2 earlier. |
|||
JSR NewLine ;hardware-dependent newline routine |
|||
ADDQ.W #1,D1 |
|||
CMP.W #6,D1 ;are we done yet? |
|||
BCS .outerloop ;if not, go back to the top |
|||
RTS</syntaxhighlight> |
|||
=={{header|8086 Assembly}}== |
|||
The following works with MS-DOS. Called as a subroutine (i.e. "call StarSub") |
|||
<syntaxhighlight lang="asm">StarSub: |
|||
mov ah,02h ;needed to prime the interrupt command for printing to screen |
|||
mov ch,1 ;outer loop counter |
|||
outer_loop: |
|||
mov cl,ch ;refresh the inner loop counter, by copying the value of the outer loop counter to it. |
|||
;each time the inner loop finishes, it will last one iteration longer the next time. |
|||
inner_loop: |
|||
mov dl,02Ah ;ascii for * |
|||
int 21h ;tells DOS to print the contents of dl to the screen |
|||
dec cl |
|||
jnz inner_loop |
|||
mov dl,13 ;Carriage Return |
|||
int 21h |
|||
mov dl,10 ;New Line |
|||
int 21h |
|||
inc ch ;make the outer loop counter bigger for next time. |
|||
cmp ch,5 |
|||
jnz outer_loop |
|||
ret</syntaxhighlight> |
|||
=={{header|8th}}== |
=={{header|8th}}== |
||
This illustrates two kinds of 'for' loop. The first kind is "loop", which iterates from the low to the high value, and passes the current loop index as a parameter to the inner word. The second is 'times', which takes a count and repeats the word that many times. |
This illustrates two kinds of 'for' loop. The first kind is "loop", which iterates from the low to the high value, and passes the current loop index as a parameter to the inner word. The second is 'times', which takes a count and repeats the word that many times. |
||
< |
<syntaxhighlight lang="forth"> |
||
( ( '* putc ) swap times cr ) 1 5 loop |
( ( '* putc ) swap times cr ) 1 5 loop |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program loop64.s */ |
/* program loop64.s */ |
||
Line 178: | Line 222: | ||
/* for this file see task include a file in language AArch64 assembly */ |
/* for this file see task include a file in language AArch64 assembly */ |
||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">Proc Main() |
|||
byte I,J |
|||
For I=1 to 5 |
|||
Do |
|||
For J=1 to I |
|||
Do |
|||
Print("*") |
|||
Od |
|||
PrintE("") |
|||
Od |
|||
Return</syntaxhighlight> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">var str:String = ""; |
||
for (var i:int = 1; i <= 5; i++) { |
for (var i:int = 1; i <= 5; i++) { |
||
for (var j:int = 1; j <= i; j++) |
for (var j:int = 1; j <= i; j++) |
||
Line 186: | Line 246: | ||
trace(str); |
trace(str); |
||
str = ""; |
str = ""; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">for I in 1..5 loop |
||
for J in 1..I loop |
for J in 1..I loop |
||
Put("*"); |
Put("*"); |
||
end loop; |
end loop; |
||
New_Line; |
New_Line; |
||
end loop;</ |
end loop;</syntaxhighlight> |
||
=={{header|Agena}}== |
=={{header|Agena}}== |
||
Tested with Agena 2.9.5 Win32 |
Tested with Agena 2.9.5 Win32 |
||
< |
<syntaxhighlight lang="agena">for i to 5 do |
||
for j to i do |
for j to i do |
||
write( "*" ) |
write( "*" ) |
||
od; |
od; |
||
print() |
print() |
||
od</ |
od</syntaxhighlight> |
||
=={{header|ALGOL 60}}== |
=={{header|ALGOL 60}}== |
||
< |
<syntaxhighlight lang="algol60">INTEGER I,J; |
||
FOR I:=1 STEP 1 UNTIL 5 DO |
FOR I:=1 STEP 1 UNTIL 5 DO |
||
BEGIN |
BEGIN |
||
Line 213: | Line 273: | ||
OUTLINE |
OUTLINE |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 221: | Line 281: | ||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
||
< |
<syntaxhighlight lang="algol68">FOR i TO 5 DO |
||
TO i DO |
TO i DO |
||
print("*") |
print("*") |
||
OD; |
OD; |
||
print(new line) |
print(new line) |
||
OD</ |
OD</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 238: | Line 298: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
In Algol W, write starts a new line, writeon continues it. |
In Algol W, write starts a new line, writeon continues it. |
||
< |
<syntaxhighlight lang="algolw">begin |
||
for i := 1 until 5 do |
for i := 1 until 5 do |
||
begin |
begin |
||
Line 247: | Line 307: | ||
end j |
end j |
||
end i |
end i |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|ALGOL-M}}== |
=={{header|ALGOL-M}}== |
||
< |
<syntaxhighlight lang="algol">BEGIN |
||
INTEGER I, J; |
INTEGER I, J; |
||
FOR I := 1 STEP 1 UNTIL 5 DO |
FOR I := 1 STEP 1 UNTIL 5 DO |
||
Line 258: | Line 318: | ||
WRITEON( "*" ); |
WRITEON( "*" ); |
||
END; |
END; |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>* |
<pre>* |
||
Line 268: | Line 328: | ||
=={{header|Alore}}== |
=={{header|Alore}}== |
||
< |
<syntaxhighlight lang="alore">for i in 0 to 6 |
||
for j in 0 to i |
for j in 0 to i |
||
Write('*') |
Write('*') |
||
Line 274: | Line 334: | ||
WriteLn() |
WriteLn() |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AmigaE}}== |
=={{header|AmigaE}}== |
||
< |
<syntaxhighlight lang="amigae">PROC main() |
||
DEF i, j |
DEF i, j |
||
FOR i := 1 TO 5 |
FOR i := 1 TO 5 |
||
Line 283: | Line 343: | ||
WriteF('\n') |
WriteF('\n') |
||
ENDFOR |
ENDFOR |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|Apex}}== |
=={{header|Apex}}== |
||
< |
<syntaxhighlight lang="java">for (Integer i = 0; i < 5; i++) { |
||
String line = ''; |
String line = ''; |
||
Line 306: | Line 366: | ||
for (String line : lines) { |
for (String line : lines) { |
||
System.debug(line); |
System.debug(line); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|APL}}== |
|||
For most purposes, the APL analogue of a for loop is the '''each''' operator <tt>¨</tt>. The most natural way to accomplish this task doesn't use a nested '''each''', but the '''repeat''' operator <tt>/</tt> inside a single '''each''': |
|||
<syntaxhighlight lang="apl">stars ← { ⍵ 1 ⍴ {⍵/'*'}¨⍳⍵ }</syntaxhighlight> |
|||
To stick to the letter of the task description, we can nest an '''each''' inside another one, but it's a little silly. Plus not all dialects support niladic dfns, so the innermost "return one star" function has to take a dummy argument: |
|||
<syntaxhighlight lang="apl">stars ← { ⍵ 1 ⍴ { {1⌷'*',⍵} ¨ ⍳⍵ } ¨ ⍳⍵ }</syntaxhighlight> |
|||
Additionally, Dyalog and some other dialects support the more traditional structured programming controls inside a named function definition (tradfn): |
|||
{{works with|Dyalog APL}} |
|||
<syntaxhighlight lang="apl">∇result ← stars count; i; j; vec |
|||
vec ← ⍬ |
|||
:for i :in ⍳ count |
|||
vec ,← ⊂'' |
|||
:for j :in ⍳ i |
|||
vec[i],←'*' |
|||
:endfor |
|||
:endfor |
|||
result ← count 1 ⍴ vec |
|||
∇</syntaxhighlight> |
|||
{{Out}} |
|||
The result of all three implementations of '''stars''' is a column vector, which is displayed like this: |
|||
<pre> stars 5 |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
*****</pre> |
|||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">set x to linefeed |
||
repeat with i from 1 to 5 |
repeat with i from 1 to 5 |
||
repeat with j from 1 to i |
repeat with j from 1 to i |
||
set x to x & "*" |
set x to x & "*" |
||
end repeat |
end repeat |
||
set x to x & |
set x to x & linefeed |
||
end repeat |
end repeat |
||
return x</ |
return x</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>* |
|||
* |
|||
** |
** |
||
*** |
*** |
||
**** |
**** |
||
***** |
*****</pre> |
||
" </pre> |
|||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program loop1.s */ |
/* program loop1.s */ |
||
Line 395: | Line 488: | ||
bx lr /* return */ |
bx lr /* return */ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">loop 0..5 'x [ |
||
loop 0.. |
loop 0..x 'y [ |
||
prints "*" |
prints "*" |
||
] |
|||
print "" |
print "" |
||
]</syntaxhighlight> |
|||
}</lang> |
|||
{{out}} |
{{out}} |
||
<pre>* |
<pre>* |
||
Line 411: | Line 504: | ||
***** |
***** |
||
******</pre> |
******</pre> |
||
=={{header|Asymptote}}== |
|||
Asymptote's control structures are similar to those in C, C++, or Java |
|||
<syntaxhighlight lang="asymptote">for(int i = 0; i < 6; ++i) { |
|||
for(int j = 0; j < i; ++j) { |
|||
write("*", suffix=none); |
|||
} |
|||
write(""); |
|||
}</syntaxhighlight> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">Gui, Add, Edit, vOutput r5 w100 -VScroll ; Create an Edit-Control |
||
Gui, Show ; Show the window |
Gui, Show ; Show the window |
||
Loop, 5 ; loop 5 times |
Loop, 5 ; loop 5 times |
||
Line 425: | Line 527: | ||
Output .= (A_Index = 5) ? "" : "`n" ; append a new line to the output if A_Index is not "5" |
Output .= (A_Index = 5) ? "" : "`n" ; append a new line to the output if A_Index is not "5" |
||
} |
} |
||
Return ; End of auto-execution section</ |
Return ; End of auto-execution section</syntaxhighlight> |
||
=={{header|Avail}}== |
=={{header|Avail}}== |
||
< |
<syntaxhighlight lang="avail">For each row from 1 to 5 do |
||
[ |
[ |
||
For each length from 1 to row do [Print: "*";]; |
For each length from 1 to row do [Print: "*";]; |
||
Print: "\n"; |
Print: "\n"; |
||
];</ |
];</syntaxhighlight> |
||
Since the inner loop index is unneeded, it may be more natural to use the <code>From_to_do_</code> loop format: |
Since the inner loop index is unneeded, it may be more natural to use the <code>From_to_do_</code> loop format: |
||
< |
<syntaxhighlight lang="avail">For each row from 1 to 5 do |
||
[ |
[ |
||
From 1 to row do [Print: "*";]; |
From 1 to row do [Print: "*";]; |
||
Print: "\n"; |
Print: "\n"; |
||
];</ |
];</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">BEGIN { |
||
for(i=1; i < 6; i++) { |
for(i=1; i < 6; i++) { |
||
for(j=1; j <= i; j++ ) { |
for(j=1; j <= i; j++ ) { |
||
Line 449: | Line 551: | ||
print |
print |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
In this example, the Axe code is nearly identical to the [[#TI-83_BASIC|TI-83 BASIC]] version. However, note the swapped order of the I and J in the Output() statement. Also, unlike TI-83 BASIC, Axe does not support an increment value other than 1. |
In this example, the Axe code is nearly identical to the [[#TI-83_BASIC|TI-83 BASIC]] version. However, note the swapped order of the I and J in the Output() statement. Also, unlike TI-83 BASIC, Axe does not support an increment value other than 1. |
||
< |
<syntaxhighlight lang="axe">ClrHome |
||
For(I,1,5) |
For(I,1,5) |
||
For(J,1,I) |
For(J,1,I) |
||
Output(J,I,"*") |
Output(J,I,"*") |
||
End |
End |
||
End</ |
End</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<syntaxhighlight lang="babel">((main { 10 star_triangle ! }) |
||
(star_triangle { |
(star_triangle { |
||
Line 472: | Line 574: | ||
"\n" << } |
"\n" << } |
||
-> |
-> |
||
times }))</ |
times }))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 488: | Line 590: | ||
The key operator here is 'iter' which gives the current iteration of the loop body it |
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. |
resides in. When used with the 'times' operator, it generates a countdown. |
||
=={{header|Bait}}== |
|||
<syntaxhighlight lang="bait"> |
|||
const ROWS := 5 |
|||
fun main() { |
|||
for i := 1; i <= ROWS; i += 1 { |
|||
for j := 1; j <= i; j += 1 { |
|||
print('*') |
|||
} |
|||
println('') |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|bash}}== |
=={{header|bash}}== |
||
< |
<syntaxhighlight lang="bash"> |
||
for i in {1..5} |
for i in {1..5} |
||
do |
do |
||
Line 499: | Line 616: | ||
echo |
echo |
||
done |
done |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
< |
<syntaxhighlight lang="qbasic">for i = 1 to 5 |
||
for j = 1 to i |
for j = 1 to i |
||
print "*"; |
print "*"; |
||
next j |
next j |
||
print |
print |
||
next i</ |
next i</syntaxhighlight> |
||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
< |
<syntaxhighlight lang="applesoftbasic">FOR I = 1 TO 5 : FOR J = 1 TO I : PRINT "*"; : NEXT J : PRINT : NEXT</syntaxhighlight> |
||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
< |
<syntaxhighlight lang="basic256">for i = 1 to 5 |
||
for j = 1 to i |
for j = 1 to i |
||
print "*"; |
print "*"; |
||
Line 520: | Line 637: | ||
print |
print |
||
next i |
next i |
||
end</ |
end</syntaxhighlight> |
||
==={{header|BaCon}}=== |
==={{header|BaCon}}=== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
FOR i = 1 TO 5 |
FOR i = 1 TO 5 |
||
FOR j = 1 TO i |
FOR j = 1 TO i |
||
Line 530: | Line 647: | ||
PRINT |
PRINT |
||
NEXT |
NEXT |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
<lang> |
<syntaxhighlight lang="text"> |
||
FOR I% = 1 TO 5 |
FOR I% = 1 TO 5 |
||
FOR J% = 1 TO I% |
FOR J% = 1 TO I% |
||
Line 541: | Line 658: | ||
PRINT |
PRINT |
||
NEXT |
NEXT |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|Chipmunk Basic}}=== |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
<syntaxhighlight lang="qbasic">10 for i = 1 to 5 |
|||
20 for j = 1 to i |
|||
30 print "*"; |
|||
40 next j |
|||
50 print |
|||
60 next i</syntaxhighlight> |
|||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
< |
<syntaxhighlight lang="qbasic">10 FOR I = 1 TO 5 |
||
20 FOR J = 1 TO I |
20 : FOR J = 1 TO I |
||
30 PRINT "*"; |
30 : PRINT "*"; |
||
40 NEXT |
40 : NEXT J |
||
50 PRINT |
50 : PRINT |
||
60 NEXT</ |
60 NEXT I</syntaxhighlight> |
||
==={{header|Creative Basic}}=== |
==={{header|Creative Basic}}=== |
||
<syntaxhighlight lang="creative basic"> |
|||
<lang Creative Basic> |
|||
OPENCONSOLE |
OPENCONSOLE |
||
Line 574: | Line 700: | ||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|GW-BASIC}}=== |
==={{header|GW-BASIC}}=== |
||
< |
<syntaxhighlight lang="qbasic">10 FOR I = 1 TO 5 |
||
20 FOR J = 1 TO I |
20 FOR J = 1 TO I |
||
30 PRINT "*"; |
30 PRINT "*"; |
||
Line 583: | Line 709: | ||
50 PRINT |
50 PRINT |
||
60 NEXT I |
60 NEXT I |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|FBSL}}=== |
==={{header|FBSL}}=== |
||
< |
<syntaxhighlight lang="qbasic"> |
||
#APPTYPE CONSOLE |
#APPTYPE CONSOLE |
||
FOR dim i = 1 TO 5 |
FOR dim i = 1 TO 5 |
||
Line 594: | Line 720: | ||
PRINT |
PRINT |
||
NEXT i |
NEXT i |
||
Pause</ |
Pause</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 605: | Line 731: | ||
==={{header|FUZE BASIC}}=== |
==={{header|FUZE BASIC}}=== |
||
< |
<syntaxhighlight lang="qbasic">FOR n = 1 to 5 CYCLE |
||
FOR k = 1 to n CYCLE |
FOR k = 1 to n CYCLE |
||
print "*"; |
print "*"; |
||
Line 611: | Line 737: | ||
PRINT |
PRINT |
||
REPEAT |
REPEAT |
||
END</ |
END</syntaxhighlight> |
||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 FOR I=1 TO 5 |
||
110 FOR J=1 TO I |
110 FOR J=1 TO I |
||
120 PRINT "*"; |
120 PRINT "*"; |
||
130 NEXT |
130 NEXT |
||
140 PRINT |
140 PRINT |
||
150 NEXT</ |
150 NEXT</syntaxhighlight> |
||
==={{header|IWBASIC}}=== |
==={{header|IWBASIC}}=== |
||
<syntaxhighlight lang="iwbasic"> |
|||
<lang IWBASIC> |
|||
OPENCONSOLE |
OPENCONSOLE |
||
Line 642: | Line 768: | ||
'Could also have been written the same way as the Creative Basic example, with no LOCATE command. |
'Could also have been written the same way as the Creative Basic example, with no LOCATE command. |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|Liberty BASIC}}=== |
==={{header|Liberty BASIC}}=== |
||
Unlike some BASICs, Liberty BASIC does not require that the counter variable be specified with 'next'. |
Unlike some BASICs, Liberty BASIC does not require that the counter variable be specified with 'next'. |
||
< |
<syntaxhighlight lang="lb">for i = 1 to 5 |
||
for j = 1 to i |
for j = 1 to i |
||
print "*"; |
print "*"; |
||
next |
next |
||
print |
print |
||
next</syntaxhighlight> |
|||
next |
|||
</lang> |
|||
==={{header|MSX Basic}}=== |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|Microsoft Small Basic}}=== |
==={{header|Microsoft Small Basic}}=== |
||
< |
<syntaxhighlight lang="microsoftsmallbasic">For i = 1 To 5 |
||
For i = 1 TO 5 |
|||
For j = 1 To i |
For j = 1 To i |
||
TextWindow.Write("*") |
TextWindow.Write("*") |
||
EndFor |
EndFor |
||
TextWindow.WriteLine("") |
TextWindow.WriteLine("") |
||
EndFor |
EndFor</syntaxhighlight> |
||
</lang> |
|||
==={{header|PureBasic}}=== |
==={{header|PureBasic}}=== |
||
< |
<syntaxhighlight lang="purebasic">If OpenConsole() |
||
Define i, j |
Define i, j |
||
For i=1 To 5 |
For i=1 To 5 |
||
Line 676: | Line 801: | ||
Print(#LFCR$+"Press ENTER to quit"): Input() |
Print(#LFCR$+"Press ENTER to quit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
==={{header| |
==={{header|QBasic}}=== |
||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
Also |
|||
The [[#BASIC256|BASIC256]] solution works without any changes. |
|||
==={{header|Quite BASIC}}=== |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|Run BASIC}}=== |
==={{header|Run BASIC}}=== |
||
< |
<syntaxhighlight lang="runbasic">FOR i = 1 TO 5 |
||
FOR i = 1 TO 5 |
|||
FOR j = 1 TO i |
FOR j = 1 TO i |
||
PRINT "*"; |
PRINT "*"; |
||
NEXT j |
NEXT j |
||
PRINT |
PRINT |
||
NEXT i |
NEXT i</syntaxhighlight> |
||
</lang> |
|||
==={{header| |
==={{header|SmallBASIC}}=== |
||
<syntaxhighlight lang="qbasic"> |
|||
for a = 1 to 5 |
|||
for b = 1 to a |
|||
print "*"; |
|||
next |
|||
print |
|||
next |
|||
</syntaxhighlight> |
|||
==={{header|smart BASIC}}=== |
|||
While some versions of BASIC allow for NEXT without a variable, smart BASIC requires the variable designation. |
While some versions of BASIC allow for NEXT without a variable, smart BASIC requires the variable designation. |
||
< |
<syntaxhighlight lang="qbasic">for n = 1 to 5 |
||
for m = 1 to n |
for m = 1 to n |
||
print "*"; |
print "*"; |
||
next m |
next m |
||
print |
print |
||
next n</ |
next n</syntaxhighlight> |
||
==={{header|True BASIC}}=== |
|||
<syntaxhighlight lang="basic">FOR i = 1 TO 5 |
|||
FOR j = 1 TO i |
|||
PRINT "*"; |
|||
NEXT j |
|||
PRINT |
|||
NEXT i |
|||
END</syntaxhighlight> |
|||
==={{header|Visual Basic}}=== |
==={{header|Visual Basic}}=== |
||
'''Works with:''' VB6 |
'''Works with:''' VB6 |
||
< |
<syntaxhighlight lang="vb">Public OutConsole As Scripting.TextStream |
||
For i = 0 To 4 |
For i = 0 To 4 |
||
For j = 0 To i |
For j = 0 To i |
||
Line 709: | Line 856: | ||
Next j |
Next j |
||
OutConsole.WriteLine |
OutConsole.WriteLine |
||
Next i</ |
Next i</syntaxhighlight> |
||
==={{header|Visual Basic .NET}}=== |
==={{header|Visual Basic .NET}}=== |
||
{{works with|Visual Basic .Net 2002}} |
{{works with|Visual Basic .Net 2002}} |
||
< |
<syntaxhighlight lang="vbnet">For x As Integer = 0 To 4 |
||
For y As Integer = 0 To x |
For y As Integer = 0 To x |
||
Console.Write("*") |
Console.Write("*") |
||
Next |
Next |
||
Console.WriteLine() |
Console.WriteLine() |
||
Next</ |
Next</syntaxhighlight> |
||
==={{header|Yabasic}}=== |
==={{header|Yabasic}}=== |
||
< |
<syntaxhighlight lang="yabasic">for i = 1 to 5 |
||
for j = 1 to i |
for j = 1 to i |
||
print "*"; |
print "*"; |
||
Line 727: | Line 874: | ||
print |
print |
||
next i |
next i |
||
end</ |
end</syntaxhighlight> |
||
==={{header|ZX Spectrum Basic}}=== |
==={{header|ZX Spectrum Basic}}=== |
||
On the ZX Spectrum, we need line numbers: |
On the ZX Spectrum, we need line numbers: |
||
<syntaxhighlight lang="basic">10 FOR i = 1 TO 5 |
|||
<lang basic> |
|||
10 FOR i = 1 TO 5 |
|||
20 FOR j = 1 TO i |
20 FOR j = 1 TO i |
||
30 PRINT "*"; |
30 PRINT "*"; |
||
40 NEXT j |
40 NEXT j |
||
50 PRINT |
50 PRINT |
||
60 NEXT i |
60 NEXT i</syntaxhighlight> |
||
</lang> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
<syntaxhighlight lang="text">@ECHO OFF |
|||
<lang>@ECHO OFF |
|||
SETLOCAL ENABLEDELAYEDEXPANSION |
SETLOCAL ENABLEDELAYEDEXPANSION |
||
Line 755: | Line 898: | ||
) |
) |
||
ENDLOCAL</ |
ENDLOCAL</syntaxhighlight> |
||
=={{header|bc}}== |
=={{header|bc}}== |
||
< |
<syntaxhighlight lang="bc">for (i = 1; i <= 5; i++) { |
||
for (j = 1; j <= i; j++) "*" |
for (j = 1; j <= i; j++) "*" |
||
" |
" |
||
" |
" |
||
} |
} |
||
quit</ |
quit</syntaxhighlight> |
||
=={{header|BCPL}}== |
|||
<syntaxhighlight lang="bcpl">get "libhdr" |
|||
let start() be |
|||
for i = 1 to 5 |
|||
$( for j = 1 to i do wrch('**') |
|||
wrch('*N') |
|||
$)</syntaxhighlight> |
|||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
< |
<syntaxhighlight lang="befunge">1>:5`#@_:>"*",v |
||
| :-1< |
| :-1< |
||
^+1,+5+5<</ |
^+1,+5+5<</syntaxhighlight> |
||
=={{header|Binary Lambda Calculus}}== |
|||
The following 22-byte BLC program is generated from https://github.com/tromp/AIT/blob/master/rosetta/forloops.lam : |
|||
<pre>18 18 11 50 73 9c e7 40 b3 df cb df 38 1c bd a3 88 05 bb 00 2a 0a</pre> |
|||
=={{header|blz}}== |
=={{header|blz}}== |
||
< |
<syntaxhighlight lang="blz">for i = 1; i <= 5; i++ |
||
line = "" |
line = "" |
||
for (j = 1; j <= i; j++) |
for (j = 1; j <= i; j++) |
||
Line 777: | Line 935: | ||
end |
end |
||
print(line) |
print(line) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat"> 0:?i |
||
& whl |
& whl |
||
' ( !i+1:~>5:?i |
' ( !i+1:~>5:?i |
||
Line 788: | Line 946: | ||
) |
) |
||
& |
& |
||
);</ |
);</syntaxhighlight> |
||
=={{header|Brainf***}}== |
=={{header|Brainf***}}== |
||
< |
<syntaxhighlight lang="bf">>>+++++++[>++++++[>+<-]<-] place * in cell 3 |
||
+++++[>++[>>+<<-]<-]<< place \n in cell 4 |
+++++[>++[>>+<<-]<-]<< place \n in cell 4 |
||
+++++[ set outer loop count |
+++++[ set outer loop count |
||
Line 798: | Line 956: | ||
>[>>.<<-]>>>.<<< print line |
>[>>.<<-]>>>.<<< print line |
||
<<-] end inner loop |
<<-] end inner loop |
||
] end outer loop</ |
] end outer loop</syntaxhighlight> |
||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">1.to 5, { i | |
||
1.to i, { j | |
1.to i, { j | |
||
print "*" |
print "*" |
||
} |
} |
||
print "\n" |
print "\n" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">int i, j; |
||
for (i = 1; i <= 5; i++) { |
for (i = 1; i <= 5; i++) { |
||
for (j = 1; j <= i; j++) |
for (j = 1; j <= i; j++) |
||
putchar('*'); |
putchar('*'); |
||
puts(""); |
puts(""); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
class Program { |
class Program { |
||
Line 831: | Line 989: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp"> |
||
for(int i = 0; i < 5; ++i) { |
for(int i = 0; i < 5; ++i) { |
||
for(int j = 0; j < i; ++j) |
for(int j = 0; j < i; ++j) |
||
Line 840: | Line 998: | ||
std::cout.put('\n'); |
std::cout.put('\n'); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C3}}== |
|||
<syntaxhighlight lang="c3"> |
|||
for (int i = 0; i < 5; i++) |
|||
{ |
|||
for (int j = 1; j <= i; j++) io::print("*"); |
|||
io::printn("*"); |
|||
}</syntaxhighlight> |
|||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">shared void run() { |
||
for(i in 1..5) { |
for(i in 1..5) { |
||
Line 851: | Line 1,017: | ||
print(""); |
print(""); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Chapel}}== |
=={{header|Chapel}}== |
||
< |
<syntaxhighlight lang="chapel">for i in 1..5 { |
||
for 1..i do write('*'); |
for 1..i do write('*'); |
||
writeln(); |
writeln(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Chef}}== |
=={{header|Chef}}== |
||
< |
<syntaxhighlight lang="chef">Asterisks Omelette. |
||
This recipe prints a triangle of asterisks. |
This recipe prints a triangle of asterisks. |
||
Line 889: | Line 1,055: | ||
Pour contents of the mixing bowl into the baking dish. |
Pour contents of the mixing bowl into the baking dish. |
||
Serves 1.</ |
Serves 1.</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(doseq [i (range 5), j (range (inc i))] |
||
(print "*") |
(print "*") |
||
(if (= i j) (println)))</ |
(if (= i j) (println)))</syntaxhighlight> |
||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">start_up = proc () |
|||
po: stream := stream$primary_output() |
|||
for i: int in int$from_to(1, 5) do |
|||
for j: int in int$from_to(1, i) do |
|||
stream$putc(po, '*') |
|||
end |
|||
stream$putl(po, "") |
|||
end |
|||
end start_up</syntaxhighlight> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. Display-Triangle. |
PROGRAM-ID. Display-Triangle. |
||
Line 919: | Line 1,097: | ||
GOBACK |
GOBACK |
||
. |
. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
Line 925: | Line 1,103: | ||
With tags: |
With tags: |
||
< |
<syntaxhighlight lang="cfm"><cfloop index = "i" from = "1" to = "5"> |
||
<cfloop index = "j" from = "1" to = "#i#"> |
<cfloop index = "j" from = "1" to = "#i#"> |
||
* |
* |
||
</cfloop> |
</cfloop> |
||
< br /> |
< br /> |
||
</cfloop></ |
</cfloop></syntaxhighlight> |
||
With script: |
With script: |
||
< |
<syntaxhighlight lang="cfm"><cfscript> |
||
for( i = 1; i <= 5; i++ ) |
for( i = 1; i <= 5; i++ ) |
||
{ |
{ |
||
Line 941: | Line 1,119: | ||
writeOutput( "< br />" ); |
writeOutput( "< br />" ); |
||
} |
} |
||
</cfscript></ |
</cfscript></syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(loop for i from 1 upto 5 do |
||
(loop for j from 1 upto i do |
(loop for j from 1 upto i do |
||
(write-char #\*)) |
(write-char #\*)) |
||
(terpri))</ |
(terpri))</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="lisp">(dotimes (i 5) |
||
(dotimes (j (+ i 1)) |
(dotimes (j (+ i 1)) |
||
(write-char #\*)) |
(write-char #\*)) |
||
(terpri))</ |
(terpri))</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="lisp">(do ((i 1 (+ i 1))) |
||
((> i 5)) |
((> i 5)) |
||
(do ((j 1 (+ j 1))) |
(do ((j 1 (+ j 1))) |
||
((> j i)) |
((> j i)) |
||
(write-char #\*)) |
(write-char #\*)) |
||
(terpri))</ |
(terpri))</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="lisp">(use-package :iterate) |
||
(iter |
(iter |
||
(for i from 1 to 5) |
(for i from 1 to 5) |
||
Line 967: | Line 1,145: | ||
(for j from 1 to i) |
(for j from 1 to i) |
||
(princ #\*)) |
(princ #\*)) |
||
(terpri))</ |
(terpri))</syntaxhighlight> |
||
=={{header|Coq}}== |
=={{header|Coq}}== |
||
< |
<syntaxhighlight lang="coq">Section FOR. |
||
Variable T : Type. |
Variable T : Type. |
||
Variable body : nat -> T -> T. |
Variable body : nat -> T -> T. |
||
Line 994: | Line 1,172: | ||
) |
) |
||
0 5 nil. |
0 5 nil. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Cowgol}}== |
|||
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
|||
var i: uint8 := 1; |
|||
while i <= 5 loop |
|||
var j: uint8 := 1; |
|||
while j <= i loop |
|||
print_char('*'); |
|||
j := j + 1; |
|||
end loop; |
|||
print_nl(); |
|||
i := i + 1; |
|||
end loop;</syntaxhighlight> |
|||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
< |
<syntaxhighlight lang="crystal"> |
||
1.upto(5) do |i| |
1.upto(5) do |i| |
||
1.upto(i) do |j| |
1.upto(i) do |j| |
||
Line 1,005: | Line 1,197: | ||
puts |
puts |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or another way, more succinctly put: |
Or another way, more succinctly put: |
||
< |
<syntaxhighlight lang="crystal"> |
||
puts (1..5).map { |i| "*" * i }.join("\n") |
puts (1..5).map { |i| "*" * i }.join("\n") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio: write, writeln; |
||
void main() { |
void main() { |
||
Line 1,029: | Line 1,221: | ||
writeln(); |
writeln(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>* |
<pre>* |
||
Line 1,044: | Line 1,236: | ||
=={{header|Dao}}== |
=={{header|Dao}}== |
||
< |
<syntaxhighlight lang="dao">for( i = 1 : 5 ){ |
||
for( j = 1 : i ) io.write( '*' ) |
for( j = 1 : i ) io.write( '*' ) |
||
io.writeln() |
io.writeln() |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
< |
<syntaxhighlight lang="dart">main() { |
||
for (var i = 0; i < 5; i++) |
for (var i = 0; i < 5; i++) |
||
for (var j = 0; j < i + 1; j++) |
for (var j = 0; j < i + 1; j++) |
||
print("*"); |
print("*"); |
||
print("\n"); |
print("\n"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|dc}}== |
=={{header|dc}}== |
||
Line 1,061: | Line 1,253: | ||
{{trans|bc}} |
{{trans|bc}} |
||
< |
<syntaxhighlight lang="dc">[ |
||
[*]P [print asterisk]sz |
[*]P [print asterisk]sz |
||
lj 1 + d sj [increment j, leave it on stack]sz |
lj 1 + d sj [increment j, leave it on stack]sz |
||
Line 1,075: | Line 1,267: | ||
]sB |
]sB |
||
1 d si [i = 1, leave it on stack]sz |
1 d si [i = 1, leave it on stack]sz |
||
5 !<B [enter loop B if 5 >= i]sz</ |
5 !<B [enter loop B if 5 >= i]sz</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program LoopFor; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 1,091: | Line 1,283: | ||
Writeln; |
Writeln; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Diego}}== |
|||
<syntaxhighlight lang="diego">set_ns(rosettacode); |
|||
add_var({str},s)_value(); |
|||
add_var({str},output); |
|||
add_for({int},i)_from(1)_uptoand(5)_inc() |
|||
with_var(s)_v(); |
|||
add_for({int},j)_from(0)_upto([i])_inc() |
|||
with_var(s)_calc([s]&="*"); |
|||
; |
|||
with_var(output)_calc(&=[s]&\n); |
|||
; |
|||
me_msg([output]); |
|||
reset_ns[];</syntaxhighlight> |
|||
=={{header|DMS}}== |
=={{header|DMS}}== |
||
< |
<syntaxhighlight lang="dms">number i, j |
||
for (i = 1; i <= 5; i++) |
for (i = 1; i <= 5; i++) |
||
{ |
{ |
||
Line 1,102: | Line 1,312: | ||
} |
} |
||
Result( "\n" ) |
Result( "\n" ) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|dodo0}}== |
=={{header|dodo0}}== |
||
< |
<syntaxhighlight lang="dodo0">fun for -> var, test, body, return # define a for loop using recursion |
||
( |
( |
||
test(var) -> continue |
test(var) -> continue |
||
Line 1,138: | Line 1,348: | ||
) |
) |
||
| result |
| result |
||
exit()</ |
exit()</syntaxhighlight> |
||
=={{header|Draco}}== |
|||
<syntaxhighlight lang="draco">proc nonrec main() void: |
|||
byte i,j; |
|||
for i from 1 upto 5 do |
|||
for j from 1 upto i do |
|||
write("*") |
|||
od; |
|||
writeln() |
|||
od |
|||
corp</syntaxhighlight> |
|||
{{out}} |
|||
<pre>* |
|||
** |
|||
*** |
|||
**** |
|||
*****</pre> |
|||
=={{header|Dragon}}== |
=={{header|Dragon}}== |
||
< |
<syntaxhighlight lang="dragon">for (i = 0, i < 5, i++) { |
||
for (j = 0, j <= i, j++) { |
for (j = 0, j <= i, j++) { |
||
show "*" |
show "*" |
||
} |
} |
||
showln "" |
showln "" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
< |
<syntaxhighlight lang="delphi">var i, j : Integer; |
||
for i := 1 to 5 do begin |
for i := 1 to 5 do begin |
||
Line 1,155: | Line 1,382: | ||
Print('*'); |
Print('*'); |
||
PrintLn(''); |
PrintLn(''); |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
{{trans|Swift}} |
{{trans|Swift}} |
||
< |
<syntaxhighlight lang="dyalect">for i in 1..5 { |
||
for _ in 1..i { |
for _ in 1..i { |
||
print("*", terminator |
print("*", terminator: "") |
||
} |
} |
||
print() |
print() |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,177: | Line 1,404: | ||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">for width in 1..5 { |
||
for _ in 1..width { |
for _ in 1..width { |
||
print("*") |
print("*") |
||
} |
} |
||
println() |
println() |
||
}</ |
}</syntaxhighlight> |
||
This loop is a combination of <code>for ... in ...</code> which iterates over something and <code>a..b</code> which is a range object that is iteratable. (Also, writing <code>a..!b</code> excludes the value b.) |
This loop is a combination of <code>for ... in ...</code> which iterates over something and <code>a..b</code> which is a range object that is iteratable. (Also, writing <code>a..!b</code> excludes the value b.) |
||
Line 1,188: | Line 1,415: | ||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
<syntaxhighlight lang="text"> |
|||
<lang>for i range 5 |
|||
for i = 1 to 5 |
|||
for j |
for j = 1 to i |
||
write "*" |
|||
. |
. |
||
print |
print "" |
||
. |
|||
.</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Ed}}== |
|||
Uses unary <tt>i</tt>-encoded numbers for state and turns them into asterisks before printing. |
|||
<syntaxhighlight> |
|||
H |
|||
a |
|||
iiiii |
|||
. |
|||
s/\B/\ |
|||
/g |
|||
a |
|||
. |
|||
y |
|||
d |
|||
g/i/x\ |
|||
s/.*/&*/\ |
|||
-1d\ |
|||
y |
|||
,p |
|||
Q |
|||
</syntaxhighlight> |
|||
=={{header|EDSAC order code}}== |
=={{header|EDSAC order code}}== |
||
Line 1,202: | Line 1,454: | ||
Characters are encoded in five-bit form, with each code point producing a different character depending on whether the machine is in 'letter' or 'figure' mode: this is why it is necessary to output a 'figure shift' control character at the beginning of the job. |
Characters are encoded in five-bit form, with each code point producing a different character depending on whether the machine is in 'letter' or 'figure' mode: this is why it is necessary to output a 'figure shift' control character at the beginning of the job. |
||
< |
<syntaxhighlight lang="edsac">[ Loops |
||
===== |
===== |
||
Line 1,251: | Line 1,503: | ||
[ 24 ] P0F [ used to clear a ] |
[ 24 ] P0F [ used to clear a ] |
||
EZPF [ begin execution ]</ |
EZPF [ begin execution ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>+ |
<pre>+ |
||
Line 1,260: | Line 1,512: | ||
=={{header|EGL}}== |
=={{header|EGL}}== |
||
< |
<syntaxhighlight lang="egl">str string; |
||
for ( i int to 5 ) |
for ( i int to 5 ) |
||
str = ""; |
str = ""; |
||
Line 1,267: | Line 1,519: | ||
end |
end |
||
SysLib.writeStdout(str); |
SysLib.writeStdout(str); |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Ela}}== |
=={{header|Ela}}== |
||
< |
<syntaxhighlight lang="ela">open monad io |
||
loop m n | n < m = do |
loop m n | n < m = do |
||
Line 1,283: | Line 1,535: | ||
| else = do return () |
| else = do return () |
||
_ = loop 10 1 ::: IO</ |
_ = loop 10 1 ::: IO</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang="ela">** |
||
*** |
*** |
||
**** |
**** |
||
Line 1,296: | Line 1,548: | ||
******** |
******** |
||
********* |
********* |
||
**********</ |
**********</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA |
ELENA 6.x : |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
public program() |
public program() |
||
{ |
{ |
||
for(int i := 0 |
for(int i := 0; i < 5; i += 1) |
||
{ |
{ |
||
for(int j := 0 |
for(int j := 0; j <= i; j += 1) |
||
{ console.write |
{ console.write("*") }; |
||
console.writeLine() |
console.writeLine() |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,322: | Line 1,574: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Loops do |
||
def loops_for(n) do |
def loops_for(n) do |
||
Enum.each(1..n, fn i -> |
Enum.each(1..n, fn i -> |
||
Line 1,331: | Line 1,583: | ||
end |
end |
||
Loops.loops_for(5)</ |
Loops.loops_for(5)</syntaxhighlight> |
||
one line (Comprehensions) |
one line (Comprehensions) |
||
< |
<syntaxhighlight lang="elixir">for i <- 1..5, do: IO.puts (for j <- 1..i, do: "*")</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
|||
<syntaxhighlight lang="lisp">;; Lisp implementation of c-for is like: |
|||
;; (let ((i nil)) |
|||
;; (while (progn (setq i (if (not i) 0 (1+ i) )) ;; if value of i is nil, initialize its value to 0, if else, add 1 |
|||
;; (< i 10)) ;; end loop when i > 10 |
|||
;; (... body ...) ) ) ;; loop body |
|||
(let ((i nil) (str "")) |
|||
(while (progn (setq i (if (not i) 0 (1+ i) )) |
|||
(< i 5)) |
|||
(setq str (concat str "*")) |
|||
(message str) ) )</syntaxhighlight> |
|||
output logged in buffer *Messages*: |
|||
<pre> |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
</pre> |
|||
=={{header|EMal}}== |
|||
<syntaxhighlight lang="emal"> |
|||
for int i = 0; i < 5; ++i |
|||
for int j = 0; j <= i; ++j do write("*") end |
|||
writeLine() |
|||
end |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">%% Implemented by Arjun Sunel |
||
-module(nested_loops). |
-module(nested_loops). |
||
-export([main/0, inner_loop/0]). |
-export([main/0, inner_loop/0]). |
||
Line 1,361: | Line 1,652: | ||
io:format("~n"), |
io:format("~n"), |
||
inner_loop(N). |
inner_loop(N). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
FOR I=1 TO 5 DO |
FOR I=1 TO 5 DO |
||
FOR J=1 TO I DO |
FOR J=1 TO I DO |
||
Line 1,371: | Line 1,662: | ||
PRINT |
PRINT |
||
END FOR |
END FOR |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
<syntaxhighlight lang="euphoria"> |
|||
<lang Euphoria> |
|||
for i = 1 to 5 do |
for i = 1 to 5 do |
||
for j = 1 to i do |
for j = 1 to i do |
||
Line 1,382: | Line 1,673: | ||
puts(1, "\n") -- Same as "puts(1, {'\n'})" |
puts(1, "\n") -- Same as "puts(1, {'\n'})" |
||
end for |
end for |
||
</syntaxhighlight> |
|||
</lang> |
|||
<code>puts()</code> is a function that takes two arguments; an <code>integer</code> and a <code>sequence</code>. Strings are simply <code>sequence</code>s; there is no string type. |
<code>puts()</code> is a function that takes two arguments; an <code>integer</code> and a <code>sequence</code>. Strings are simply <code>sequence</code>s; there is no string type. |
||
Line 1,389: | Line 1,680: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">#light |
||
[<EntryPoint>] |
[<EntryPoint>] |
||
let main args = |
let main args = |
||
Line 1,396: | Line 1,687: | ||
printf "*" |
printf "*" |
||
printfn "" |
printfn "" |
||
0</ |
0</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">5 [1,b] [ [ "*" write ] times nl ] each</syntaxhighlight> |
||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
< |
<syntaxhighlight lang="false">1[$6-][$[$]["*"1-]#%" |
||
"1+]#%</ |
"1+]#%</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
Line 1,409: | Line 1,700: | ||
Using for loops: |
Using for loops: |
||
< |
<syntaxhighlight lang="fantom"> |
||
class ForLoops |
class ForLoops |
||
{ |
{ |
||
Line 1,424: | Line 1,715: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using range objects: |
Using range objects: |
||
< |
<syntaxhighlight lang="fantom"> |
||
class ForLoops |
class ForLoops |
||
{ |
{ |
||
Line 1,443: | Line 1,734: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fennel}}== |
|||
<syntaxhighlight lang="fennel">(for [i 1 4] |
|||
(for [j 1 i] |
|||
(io.write "*")) |
|||
(print)) |
|||
</syntaxhighlight> |
|||
=={{header|Fermat}}== |
|||
<syntaxhighlight lang="fermat"> |
|||
for i = 1 to 5 do for j = 1 to i do !'*'; od; !; od |
|||
</syntaxhighlight> |
|||
=={{header|FOCAL}}== |
=={{header|FOCAL}}== |
||
When the program exits the outer loop, the control variable <tt>I</tt> is set to 4 + 1 = 5; we can therefore permit execution to fall through into the inner loop for one more iteration. |
When the program exits the outer loop, the control variable <tt>I</tt> is set to 4 + 1 = 5; we can therefore permit execution to fall through into the inner loop for one more iteration. |
||
< |
<syntaxhighlight lang="focal">01.10 FOR I=1,4; DO 2.0 |
||
02.10 FOR J=1,I; TYPE "*" |
02.10 FOR J=1,I; TYPE "*" |
||
02.20 TYPE !</ |
02.20 TYPE !</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,460: | Line 1,763: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: triangle ( n -- ) |
||
1+ 1 do |
1+ 1 do |
||
cr i 0 do [char] * emit loop |
cr i 0 do [char] * emit loop |
||
loop ; |
loop ; |
||
5 triangle</ |
5 triangle</syntaxhighlight> |
||
One more: |
One more: |
||
< |
<syntaxhighlight lang="forth"> |
||
: limit_example |
: limit_example |
||
15 1 do r> r@ dup rot >r drop \ Bring limit on stack |
15 1 do r> r@ dup rot >r drop \ Bring limit on stack |
||
Line 1,472: | Line 1,775: | ||
loop ; |
loop ; |
||
\ Gforth and JSForth all work, SP-Forth brakes (different 'for' implementation?) |
\ Gforth and JSForth all work, SP-Forth brakes (different 'for' implementation?) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|77 and later}} |
{{works with|Fortran|77 and later}} |
||
< |
<syntaxhighlight lang="fortran">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 one nonstandard character on the line labelled 5001. Many F77 |
||
C compilers should be okay with it, but it is *not* standard. |
C compilers should be okay with it, but it is *not* standard. |
||
Line 1,508: | Line 1,811: | ||
5001 FORMAT (A, $) |
5001 FORMAT (A, $) |
||
C5001 FORMAT (A, ADVANCE='NO') |
C5001 FORMAT (A, ADVANCE='NO') |
||
END</ |
END</syntaxhighlight> |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">DO i = 1, 5 |
||
DO j = 1, i |
DO j = 1, i |
||
WRITE(*, "(A)", ADVANCE="NO") "*" |
WRITE(*, "(A)", ADVANCE="NO") "*" |
||
END DO |
END DO |
||
WRITE(*,*) |
WRITE(*,*) |
||
END DO</ |
END DO</syntaxhighlight> |
||
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. |
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|95 and later}} |
{{works with|Fortran|95 and later}} |
||
< |
<syntaxhighlight lang="fortran">integer :: i |
||
integer, dimension(10) :: v |
integer, dimension(10) :: v |
||
forall (i=1:size(v)) v(i) = i</ |
forall (i=1:size(v)) v(i) = i</syntaxhighlight> |
||
But if one accepts that a do-loop can be expressed without the actual word "do" (or "for"), then |
But if one accepts that a do-loop can be expressed without the actual word "do" (or "for"), then |
||
<syntaxhighlight lang="fortran"> |
|||
<lang Fortran> |
|||
DO 1 I = 1,5 |
DO 1 I = 1,5 |
||
1 WRITE (6,*) ("*", J = 1,I) |
1 WRITE (6,*) ("*", J = 1,I) |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
That is a complete programme, though a more polite source file would have INTEGER I,J. It uses the old-style DO ''label'' etc. style of DO-loop to save on having to specify an END DO. The WRITE statement's output list is generated by an "implied" DO-loop having much of the form of DO J = 1,I and is indeed a proper loop. The output item is a text literal, which in earlier Fortran was unknown, however the result can still be achieved: |
That is a complete programme, though a more polite source file would have INTEGER I,J. It uses the old-style DO ''label'' etc. style of DO-loop to save on having to specify an END DO. The WRITE statement's output list is generated by an "implied" DO-loop having much of the form of DO J = 1,I and is indeed a proper loop. The output item is a text literal, which in earlier Fortran was unknown, however the result can still be achieved: |
||
<syntaxhighlight lang="fortran"> |
|||
<lang Fortran> |
|||
DO 1 I = 1,5 |
DO 1 I = 1,5 |
||
1 WRITE (6,2) (666, J = 1,I) |
1 WRITE (6,2) (666, J = 1,I) |
||
2 FORMAT(5I1) |
2 FORMAT(5I1) |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
This works because if a value cannot be fitted into its output field, the field is filled with asterisks. Which, is what is wanted! Just allow one digit for output (I1), and present a large integer. |
This works because if a value cannot be fitted into its output field, the field is filled with asterisks. Which, is what is wanted! Just allow one digit for output (I1), and present a large integer. |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
For i As Integer = 1 To 5 |
For i As Integer = 1 To 5 |
||
Line 1,551: | Line 1,854: | ||
Next |
Next |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,563: | Line 1,866: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang="frink"> |
||
for n = 1 to 5 |
for n = 1 to 5 |
||
{ |
{ |
||
Line 1,571: | Line 1,874: | ||
println[] |
println[] |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Futhark}}== |
=={{header|Futhark}}== |
||
Line 1,579: | Line 1,882: | ||
inner loop. |
inner loop. |
||
<syntaxhighlight lang="futhark"> |
|||
<lang Futhark> |
|||
fun main(n: int): [n]int = |
fun main(n: int): [n]int = |
||
loop (a = replicate n 0) = for i < n do |
loop (a = replicate n 0) = for i < n do |
||
Line 1,587: | Line 1,890: | ||
in a) |
in a) |
||
in a |
in a |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FutureBasic}}== |
|||
<syntaxhighlight lang="futurebasic">window 1 |
|||
long i, j |
|||
for i = 1 to 5 |
|||
for j = 1 to i |
|||
print @"*"; |
|||
next |
|||
print |
|||
next |
|||
HandleEvents</syntaxhighlight> |
|||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=9be4a2a6e69b2bf2921279a057df18c5 Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=9be4a2a6e69b2bf2921279a057df18c5 Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim i, j As Integer |
Dim i, j As Integer |
||
Line 1,601: | Line 1,918: | ||
Next |
Next |
||
End</ |
End</syntaxhighlight> |
||
<pre> |
<pre> |
||
* |
* |
||
Line 1,611: | Line 1,928: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">for i in [1 .. 5] do |
||
for j in [1 .. i] do |
for j in [1 .. i] do |
||
Print("*"); |
Print("*"); |
||
Line 1,622: | Line 1,939: | ||
# *** |
# *** |
||
# **** |
# **** |
||
# *****</ |
# *****</syntaxhighlight> |
||
=={{header|GML}}== |
=={{header|GML}}== |
||
< |
<syntaxhighlight lang="gml">pattern = "" |
||
for(i = 1; i <= 5; i += 1) |
for(i = 1; i <= 5; i += 1) |
||
{ |
{ |
||
Line 1,634: | Line 1,951: | ||
pattern += "#" |
pattern += "#" |
||
} |
} |
||
show_message(pattern)</ |
show_message(pattern)</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,648: | Line 1,965: | ||
fmt.Printf("\n") |
fmt.Printf("\n") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,660: | Line 1,977: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">for(i in (1..6)) { |
||
for(j in (1..i)) { |
for(j in (1..i)) { |
||
print '*' |
print '*' |
||
} |
} |
||
println () |
println () |
||
}</ |
}</syntaxhighlight> |
||
=={{header|GW-BASIC}}== |
=={{header|GW-BASIC}}== |
||
< |
<syntaxhighlight lang="qbasic">100 FOR I=1 TO 5 |
||
110 FOR J=1 TO I |
110 FOR J=1 TO I |
||
120 PRINT "*"; |
120 PRINT "*"; |
||
Line 1,674: | Line 1,991: | ||
140 PRINT |
140 PRINT |
||
150 NEXT I |
150 NEXT I |
||
160 END</ |
160 END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,686: | Line 2,003: | ||
=={{header|Hack}}== |
=={{header|Hack}}== |
||
< |
<syntaxhighlight lang="hack">for($i = 0; $i < 5; $i++) { |
||
for($j = 0; $j <= $i; $j++) { |
for($j = 0; $j <= $i; $j++) { |
||
echo '*'; |
echo '*'; |
||
Line 1,692: | Line 2,009: | ||
echo '\n'; |
echo '\n'; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad |
||
main = do |
main = do |
||
Line 1,701: | Line 2,018: | ||
forM_ [1..i] $ \j -> do |
forM_ [1..i] $ \j -> do |
||
putChar '*' |
putChar '*' |
||
putChar '\n'</ |
putChar '\n'</syntaxhighlight> |
||
But it's more Haskellish to do this without loops: |
But it's more Haskellish to do this without loops: |
||
< |
<syntaxhighlight lang="haskell">import Data.List (inits) |
||
main = mapM_ putStrLn $ tail $ inits $ replicate 5 '*'</ |
main = mapM_ putStrLn $ tail $ inits $ replicate 5 '*'</syntaxhighlight> |
||
Or, with a list comprehension: |
|||
<syntaxhighlight lang="haskell">putStrLn $ unlines [replicate n '*' | n <- [1..5]]</syntaxhighlight> |
|||
Taking from an infinite stream of increasing length lines: |
|||
<syntaxhighlight lang="haskell">putStrLn . unlines . take 5 $ iterate ('*':) "*"</syntaxhighlight> |
|||
=={{header|Haxe}}== |
=={{header|Haxe}}== |
||
< |
<syntaxhighlight lang="haxe">for (i in 1...6) { |
||
for(j in 0...i) { |
for(j in 0...i) { |
||
Sys.print('*'); |
Sys.print('*'); |
||
} |
} |
||
Sys.println(''); |
Sys.println(''); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|hexiscript}}== |
=={{header|hexiscript}}== |
||
< |
<syntaxhighlight lang="hexiscript">for let i 1; i <= 5; i++ |
||
for let j 1; j <= i; j++ |
for let j 1; j <= i; j++ |
||
print "*" |
print "*" |
||
endfor |
endfor |
||
println "" |
println "" |
||
endfor</ |
endfor</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">DO i = 1, 5 |
||
DO j = 1, i |
DO j = 1, i |
||
WRITE(APPend) "*" |
WRITE(APPend) "*" |
||
ENDDO |
ENDDO |
||
WRITE() ' ' |
WRITE() ' ' |
||
ENDDO</ |
ENDDO</syntaxhighlight> |
||
=={{header|HolyC}}== |
=={{header|HolyC}}== |
||
< |
<syntaxhighlight lang="holyc">U8 i, j; |
||
for (i = 1; i <= 5; i++) { |
for (i = 1; i <= 5; i++) { |
||
for (j = 1; j <= i; j++) |
for (j = 1; j <= i; j++) |
||
Print("*"); |
Print("*"); |
||
Print("\n"); |
Print("\n"); |
||
}</ |
}</syntaxhighlight> |
||
== Icon and Unicon == |
== Icon and Unicon == |
||
==={{header|Icon}}=== |
==={{header|Icon}}=== |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
every i := 1 to 5 do { |
every i := 1 to 5 do { |
||
every 1 to i do |
every 1 to i do |
||
Line 1,750: | Line 2,075: | ||
write() |
write() |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
==={{header|Unicon}}=== |
==={{header|Unicon}}=== |
||
The Icon solution works in Unicon. |
The Icon solution works in Unicon. |
||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
< |
<syntaxhighlight lang="inform7">repeat with length running from 1 to 5: |
||
repeat with N running from 1 to length: |
repeat with N running from 1 to length: |
||
say "*"; |
say "*"; |
||
say line break;</ |
say line break;</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
J is array-oriented, so there is very little need for loops. For example |
J is array-oriented, so there is very little need for loops. For example: |
||
<syntaxhighlight lang=J> |
|||
]\ '*****' |
]\ '*****' |
||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
</syntaxhighlight> |
|||
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 |
<syntaxhighlight lang="j">{{ |
||
for_i. i. y do. |
|||
z=. '' |
|||
for. i. i do. |
|||
z=. z,'*' |
|||
end. |
|||
z=. z,'*' |
|||
echo z |
|||
end. |
|||
EMPTY |
|||
z 1!:2 ] 2 |
|||
}}0 |
|||
end. |
|||
</syntaxhighlight> |
|||
i.0 0 |
|||
)</lang> |
|||
But you would almost never see J code like this. |
But you would almost never see J code like this. |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">for (int i = 0; i < 5; i++) { |
||
for (int j = 0; j <= i; j++) { |
for (int j = 0; j <= i; j++) { |
||
System.out.print("*"); |
System.out.print("*"); |
||
} |
} |
||
System.out.println(); |
System.out.println(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">var i, j; |
||
for (i = 1; i <= 5; i += 1) { |
for (i = 1; i <= 5; i += 1) { |
||
s = ''; |
s = ''; |
||
Line 1,797: | Line 2,127: | ||
s += '*'; |
s += '*'; |
||
document.write(s + '<br>'); |
document.write(s + '<br>'); |
||
}</ |
}</syntaxhighlight> |
||
Line 1,803: | Line 2,133: | ||
or a simple range function which generates a range: |
or a simple range function which generates a range: |
||
< |
<syntaxhighlight lang="javascript">function range(i) { |
||
return i ? range(i - 1).concat(i) : []; |
return i ? range(i - 1).concat(i) : []; |
||
} |
} |
||
range(5) --> [1, 2, 3, 4, 5]</ |
range(5) --> [1, 2, 3, 4, 5]</syntaxhighlight> |
||
We could write something like: |
We could write something like: |
||
< |
<syntaxhighlight lang="javascript">var s = ''; |
||
range(5).forEach( |
range(5).forEach( |
||
Line 1,822: | Line 2,152: | ||
); |
); |
||
console.log(s);</ |
console.log(s);</syntaxhighlight> |
||
but it might be more natural in JavaScript, if we are going to use built-in Array functions, to simplify a little with '''Array.reduce()''', writing: |
but it might be more natural in JavaScript, if we are going to use built-in Array functions, to simplify a little with '''Array.reduce()''', writing: |
||
< |
<syntaxhighlight lang="javascript">console.log( |
||
range(5).reduce( |
range(5).reduce( |
||
function (a, n) { |
function (a, n) { |
||
Line 1,832: | Line 2,162: | ||
}, '' |
}, '' |
||
) |
) |
||
);</ |
);</syntaxhighlight> |
||
in which the inner ''n'' refers to the Array value visited at the next level out, and the triangle is returned as a single expression, rather than as a series of variable mutations. |
in which the inner ''n'' refers to the Array value visited at the next level out, and the triangle is returned as a single expression, rather than as a series of variable mutations. |
||
Line 1,838: | Line 2,168: | ||
Finally, in contexts where an expression composes better than a statement, the effect of a loop can often be expressed as a map. |
Finally, in contexts where an expression composes better than a statement, the effect of a loop can often be expressed as a map. |
||
< |
<syntaxhighlight lang="javascript">console.log( |
||
range(5).map(function(a) { |
range(5).map(function(a) { |
||
return Array(a + 1).join('*'); |
return Array(a + 1).join('*'); |
||
}).join('\n') |
}).join('\n') |
||
);</ |
);</syntaxhighlight> |
||
=={{header|Jinja}}== |
|||
Variable usage inside a loop, |
|||
before version 2.10 : |
|||
<syntaxhighlight lang="jinja">print(Template("""{% set sum = 0 %} |
|||
{% for i in range(6) %} |
|||
{{ sum }}{% set sum = sum + i %} |
|||
{%- endfor %}""").render()) |
|||
</syntaxhighlight> |
|||
Since 2.10 : |
|||
<syntaxhighlight lang="jinja">print(Template("""{% set sum = namespace(value=0) %} |
|||
{% for i in range(6) %} |
|||
{{ sum.value }}{% set sum.value = sum.value + i %} |
|||
{%- endfor %}""").render()) |
|||
</syntaxhighlight> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
< |
<syntaxhighlight lang="jq"># Single-string version using explicit nested loops: |
||
def demo(m): |
def demo(m): |
||
reduce range(0;m) as $i |
reduce range(0;m) as $i |
||
Line 1,857: | Line 2,202: | ||
# Variation of demo2 using an implicit inner loop: |
# Variation of demo2 using an implicit inner loop: |
||
def demo3(m): range(1;m) | "*" * . ;</ |
def demo3(m): range(1;m) | "*" * . ;</syntaxhighlight> |
||
'''Example using demo(6)''' |
'''Example using demo(6)''' |
||
{{Out}} |
{{Out}} |
||
Line 1,869: | Line 2,214: | ||
=={{header|Jsish}}== |
=={{header|Jsish}}== |
||
Code from Javascript entry. |
Code from Javascript entry. |
||
< |
<syntaxhighlight lang="javascript">var i, j, s; |
||
for (i = 1; i <= 5; i += 1) { |
for (i = 1; i <= 5; i += 1) { |
||
s = ''; |
s = ''; |
||
for (j = 0; j < i; j += 1) s += '*'; |
for (j = 0; j < i; j += 1) s += '*'; |
||
puts(s); |
puts(s); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,885: | Line 2,230: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
for i in 1:5 |
for i in 1:5 |
||
for j in 1:i |
for j in 1:i |
||
Line 1,892: | Line 2,237: | ||
println() |
println() |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,902: | Line 2,247: | ||
=={{header|Klong}}== |
=={{header|Klong}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang K> |
|||
:" x{p}:*y means repeat {p} x times starting at y " |
:" x{p}:*y means repeat {p} x times starting at y " |
||
Line 1,913: | Line 2,258: | ||
{.p(x:^0c*)}'1+!5 |
{.p(x:^0c*)}'1+!5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="kotlin">fun main(args: Array<String>) { |
||
(1..5).forEach { |
(1..5).forEach { |
||
(1..it).forEach { print('*') } |
(1..it).forEach { print('*') } |
||
println() |
println() |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|LabVIEW}}== |
=={{header|LabVIEW}}== |
||
Line 1,928: | Line 2,273: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
{def loops_for |
{def loops_for |
||
{lambda {:i :n} |
{lambda {:i :n} |
||
Line 1,944: | Line 2,289: | ||
* * * * |
* * * * |
||
* * * * * (end of loop) |
* * * * * (end of loop) |
||
</lang> |
|||
a simpler way, using {S.map function {S.serie start end [step]} |
|||
{S.map {lambda {:i} {br} |
|||
{S.map {lambda {:i} *} |
|||
{S.serie 1 :i}}} |
|||
{S.serie 1 5}} |
|||
-> |
|||
* |
|||
* * |
|||
* * * |
|||
* * * * |
|||
* * * * * |
|||
</syntaxhighlight> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">: cr "\n" . ; : dip swap '_ set execute _ ; |
||
: nip swap drop ; : last -1 extract nip ; |
: nip swap drop ; : last -1 extract nip ; |
||
: times |
: times |
||
Line 1,955: | Line 2,313: | ||
: concat "" join ; |
: concat "" join ; |
||
'* 1 5 "2dup reshape concat . cr 1 +" times</ |
'* 1 5 "2dup reshape concat . cr 1 +" times</syntaxhighlight> |
||
=={{header|langur}}== |
=={{header|langur}}== |
||
<syntaxhighlight lang="langur"> |
|||
<lang langur>for .i = 0; .i < 5; .i += 1 { |
|||
for i = 0; i < 5; i += 1 { |
|||
for j = 0; j <= i; j += 1 { |
|||
write "*" |
write "*" |
||
} |
} |
||
writeln() |
writeln() |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
A for of loop iterates over keys (when used with an array, string, or hash) and a for in loop iterates over values. |
A for of loop iterates over keys (when used with an array, string, or hash) and a for in loop iterates over values. |
||
<lang |
<syntaxhighlight lang="langur"> |
||
for i of 5 { |
|||
for of i { |
|||
write "*" |
write "*" |
||
} |
} |
||
writeln() |
writeln() |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
Or, with one for loop... |
Or, with one for loop... |
||
<lang |
<syntaxhighlight lang="langur"> |
||
for i of 5 { |
|||
writeln "*" x .i |
|||
writeln "*" * i |
|||
}</lang> |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">loop(5) => {^ |
||
loop(loop_count) => {^ '*' ^} |
loop(loop_count) => {^ '*' ^} |
||
'\r' |
'\r' |
||
^}</ |
^}</syntaxhighlight> |
||
=={{header|LC3 Assembly}}== |
=={{header|LC3 Assembly}}== |
||
< |
<syntaxhighlight lang="lc3asm"> .ORIG 0x3000 |
||
AND R1,R1,0 |
AND R1,R1,0 |
||
Line 2,016: | Line 2,380: | ||
LF .FILL 0x0A |
LF .FILL 0x0A |
||
.END</ |
.END</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>* |
<pre>* |
||
Line 2,023: | Line 2,387: | ||
**** |
**** |
||
*****</pre> |
*****</pre> |
||
=={{header|LDPL}}== |
|||
<syntaxhighlight lang="ldpl">data: |
|||
i is number |
|||
j is number |
|||
procedure: |
|||
for i from 1 to 6 step 1 do |
|||
for j from 0 to i step 1 do |
|||
display "*" |
|||
repeat |
|||
display lf |
|||
repeat |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
</pre> |
|||
=={{header|LIL}}== |
=={{header|LIL}}== |
||
In LIL '''for''' takes a before loop code block for init, a conditional expression (true to enter loop step, false to exit loop), an after each loop step code block for value reassignment, followed by the code for the loop. |
In LIL '''for''' takes a before loop code block for init, a conditional expression (true to enter loop step, false to exit loop), an after each loop step code block for value reassignment, followed by the code for the loop. |
||
< |
<syntaxhighlight lang="tcl">for {set i 1} {$i <= 5} {inc i} { |
||
for {set j 1} {$j <= $i} {inc j} { |
for {set j 1} {$j <= $i} {inc j} { |
||
write "*" |
write "*" |
||
} |
} |
||
print |
print |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,045: | Line 2,431: | ||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">repeat with i = 1 to 5 |
||
str = "" |
str = "" |
||
repeat with j = 1 to i |
repeat with j = 1 to i |
||
Line 2,051: | Line 2,437: | ||
end repeat |
end repeat |
||
put str |
put str |
||
end repeat</ |
end repeat</syntaxhighlight> |
||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang="lisaac">1.to 5 do { i : INTEGER; |
||
1.to i do { dummy : INTEGER; |
1.to i do { dummy : INTEGER; |
||
'*'.print; |
'*'.print; |
||
}; |
}; |
||
'\n'.print; |
'\n'.print; |
||
};</ |
};</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">put 0 into n |
||
repeat for 5 times |
repeat for 5 times |
||
add 1 to n |
add 1 to n |
||
Line 2,069: | Line 2,455: | ||
end repeat |
end repeat |
||
put return |
put return |
||
end repeat</ |
end repeat</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">for [i 1 5] [repeat :i [type "*] (print)] |
||
repeat 5 [repeat repcount [type "*] (print)]</ |
repeat 5 [repeat repcount [type "*] (print)]</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua"> |
||
for i=1,5 do |
for i=1,5 do |
||
for j=1,i do |
for j=1,i do |
||
Line 2,083: | Line 2,469: | ||
io.write("\n") |
io.write("\n") |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
single loop |
|||
<syntaxhighlight lang="lua">for i = 1, 5 do |
|||
print(string.rep("*", i)) |
|||
end</syntaxhighlight> |
|||
or |
|||
<syntaxhighlight lang="lua">for i = 1, 5 do |
|||
print(("*"):rep(i)) |
|||
end</syntaxhighlight> |
|||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
By default there For loops always perform on execution of block. If end value is smaller than fist value, then step adjust to that direction. When first value is equal to second value then if we declare step negative end value after execution of block became start value minus absolute step, or if step is positive, became start value plus step. We can use a switch for interpreter to change IF's STEP to act as BASIC's, and sign of step always used, and there is situations where block can't executed. |
By default there For loops always perform on execution of block. If end value is smaller than fist value, then step adjust to that direction. When first value is equal to second value then if we declare step negative end value after execution of block became start value minus absolute step, or if step is positive, became start value plus step. We can use a switch for interpreter to change IF's STEP to act as BASIC's, and sign of step always used, and there is situations where block can't executed. |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
For i=1 to 5 |
For i=1 to 5 |
||
For j=1 to i |
For j=1 to i |
||
Line 2,103: | Line 2,497: | ||
} |
} |
||
Print "End2" |
Print "End2" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">define(`for', |
||
`ifelse($#,0,``$0'', |
`ifelse($#,0,``$0'', |
||
`ifelse(eval($2<=$3),1, |
`ifelse(eval($2<=$3),1, |
||
Line 2,114: | Line 2,508: | ||
`for(`y',`1',x,`1', |
`for(`y',`1',x,`1', |
||
`*') |
`*') |
||
')</ |
')</syntaxhighlight> |
||
=={{header|make}}== |
=={{header|make}}== |
||
{{works with|BSD make}} |
{{works with|BSD make}} |
||
{{libheader|jot}} |
{{libheader|jot}} |
||
< |
<syntaxhighlight lang="make">all: line-5 |
||
ILIST != jot 5 |
ILIST != jot 5 |
||
Line 2,144: | Line 2,538: | ||
. endfor |
. endfor |
||
.endfor</ |
.endfor</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">> for i to 5 do to i do printf( "*" ) end; printf( "\n" ) end; |
||
* |
* |
||
** |
** |
||
*** |
*** |
||
**** |
**** |
||
*****</ |
*****</syntaxhighlight> |
||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
<syntaxhighlight lang="mathematica">n=5; |
|||
<lang Mathematica>n=5; |
|||
For[i=1,i<=5,i++, |
For[i=1,i<=5,i++, |
||
string=""; |
string=""; |
||
For[j=1,j<=i,j++,string=string<>"*"]; |
For[j=1,j<=i,j++,string=string<>"*"]; |
||
Print[string] |
Print[string] |
||
]</ |
]</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang="matlab">for i = (1:5) |
||
output = []; |
output = []; |
||
for j = (1:i) |
for j = (1:i) |
||
Line 2,169: | Line 2,563: | ||
end |
end |
||
disp(output); |
disp(output); |
||
end</ |
end</syntaxhighlight> |
||
Vectorized version: |
Vectorized version: |
||
< |
<syntaxhighlight lang="matlab">for i = (1:5) |
||
disp(repmat('*',1,i)); |
disp(repmat('*',1,i)); |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">for i thru 5 do ( |
||
s: "", |
s: "", |
||
thru i do s: sconcat(s, "*"), |
thru i do s: sconcat(s, "*"), |
||
print(s) |
print(s) |
||
);</ |
);</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">for i in 1 to 5 do |
||
( |
( |
||
line = "" |
line = "" |
||
Line 2,194: | Line 2,588: | ||
) |
) |
||
format "%\n" line |
format "%\n" line |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
<lang>:- module loops_for. |
<syntaxhighlight lang="text">:- module loops_for. |
||
:- interface. |
:- interface. |
||
Line 2,218: | Line 2,612: | ||
inner_loop_body(_, !IO) :- |
inner_loop_body(_, !IO) :- |
||
io.write_char('*', !IO).</ |
io.write_char('*', !IO).</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
Literal interpretation of the task is somewhat complicated by the fact that the standard implementation of <code>print</code> in MiniScript adds a line break: |
Literal interpretation of the task is somewhat complicated by the fact that the standard implementation of <code>print</code> in MiniScript adds a line break: |
||
< |
<syntaxhighlight lang="miniscript">for i in range(1,5) |
||
s = "" |
s = "" |
||
for j in range(1, i) |
for j in range(1, i) |
||
Line 2,228: | Line 2,622: | ||
end for |
end for |
||
print s |
print s |
||
end for</ |
end for</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,239: | Line 2,633: | ||
However, it is worth noting that MiniScript's string replication operator (*) makes a more natural solution possible: |
However, it is worth noting that MiniScript's string replication operator (*) makes a more natural solution possible: |
||
< |
<syntaxhighlight lang="miniscript">for i in range(1,5) |
||
print "*" * i |
print "*" * i |
||
end for</ |
end for</syntaxhighlight> |
||
(Output same as above.) |
(Output same as above.) |
||
=={{header|MIPS Assembly}}== |
|||
Thanks to [https://www.chibialiens.com/mips/ ChibiAliens] for the header and footer as well as print routines. |
|||
<syntaxhighlight lang="mips">.include "\SrcAll\Header.asm" |
|||
.include "\SrcAll\BasicMacros.asm" |
|||
.include "\SrcPSX\MemoryMap.asm" |
|||
.include "\SrcN64\MemoryMap.asm" |
|||
CursorX equ 0x100 |
|||
CursorY equ 0x101 |
|||
main: |
|||
li t3,5+1 ;outer loop counter |
|||
li t2,1 ;inner loop counter |
|||
move a2,t2 ;working copy of inner loop counter |
|||
loop: |
|||
li a1,'*' |
|||
jal PrintChar |
|||
nop ;needed on PlayStation after branches to prevent out-of-order execution. |
|||
subiu a2,1 |
|||
bnez a2,loop |
|||
nop |
|||
;overhead |
|||
jal NewLine ;this doesn't use t2 so we don't care about out-of-order execution. |
|||
addiu t2,1 ;increment outer loop counter |
|||
move a2,t2 ;next time, we'll print one more * than we did last time. |
|||
bne t2,t3,loop ;are we done yet? If not, loop. |
|||
nop |
|||
HALT: |
|||
j HALT ;halt the CPU - we're done |
|||
nop |
|||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|||
MyFont: |
|||
.ifdef buildn64 |
|||
.incbin "\ResN64\ChibiAkumas.fnt" |
|||
.endif |
|||
.ifdef buildPSX |
|||
.incbin "\ResPSX\ChibiAkumas.fnt" |
|||
.endif |
|||
.include "\SrcALL\graphics.asm" |
|||
.include "..\\SrcAll\monitor.asm" |
|||
.include "\SrcN64\Footer.asm"</syntaxhighlight> |
|||
{{out}} |
|||
<pre>* |
|||
** |
|||
*** |
|||
**** |
|||
*****</pre> |
|||
[https://ibb.co/LdmTpwP Screenshot of Nintendo 64 emulator] |
|||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE For; |
||
IMPORT InOut; |
IMPORT InOut; |
||
Line 2,259: | Line 2,708: | ||
InOut.WriteLn |
InOut.WriteLn |
||
END |
END |
||
END For.</ |
END For.</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang="modula3">MODULE Stars EXPORTS Main; |
||
IMPORT IO; |
IMPORT IO; |
||
Line 2,273: | Line 2,722: | ||
IO.Put("\n"); |
IO.Put("\n"); |
||
END; |
END; |
||
END Stars.</ |
END Stars.</syntaxhighlight> |
||
=={{header|MOO}}== |
=={{header|MOO}}== |
||
< |
<syntaxhighlight lang="moo">for i in [1..5] |
||
s = ""; |
s = ""; |
||
for j in [1..i] |
for j in [1..i] |
||
Line 2,282: | Line 2,731: | ||
endfor |
endfor |
||
player:tell(s); |
player:tell(s); |
||
endfor</ |
endfor</syntaxhighlight> |
||
=={{header|Morfa}}== |
=={{header|Morfa}}== |
||
< |
<syntaxhighlight lang="morfa"> |
||
import morfa.base; |
import morfa.base; |
||
Line 2,296: | Line 2,745: | ||
println(""); |
println(""); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
=== Routine === |
=== Routine === |
||
< |
<syntaxhighlight lang="mumps">FORLOOP |
||
NEW I,J |
NEW I,J |
||
FOR I=1:1:5 DO |
FOR I=1:1:5 DO |
||
Line 2,306: | Line 2,755: | ||
..WRITE "*" |
..WRITE "*" |
||
.WRITE ! |
.WRITE ! |
||
QUIT</ |
QUIT</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,319: | Line 2,768: | ||
=== One line === |
=== 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). |
The if statement has to follow the write, or else the if statement would control the write (5 lines with one asterisk each). |
||
< |
<syntaxhighlight lang="mumps">FOR I=1:1:5 FOR J=1:1:I WRITE "*" IF J=I W !</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang="nanoquery">for ($i = 1) ($i <= 5) ($i = $i+1) |
||
for ($j = 0) ($j < $i) ($j = $j+1) |
for ($j = 0) ($j < $i) ($j = $j+1) |
||
print "*" |
print "*" |
||
end for |
end for |
||
println |
println |
||
end for</ |
end for</syntaxhighlight> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="nemerle">for (int i = 0; i < 5; i++) |
||
{ |
{ |
||
for (int j = 0; j <= i; j++) |
for (int j = 0; j <= i; j++) |
||
Line 2,337: | Line 2,786: | ||
} |
} |
||
WriteLine(); |
WriteLine(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols nobinary |
options replace format comments java crossref savelog symbols nobinary |
||
Line 2,352: | Line 2,801: | ||
say |
say |
||
end i_ |
end i_ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
<syntaxhighlight lang="newlisp"> |
|||
<lang NewLISP> |
|||
(for (i 1 5) |
(for (i 1 5) |
||
(for(j 1 i) |
(for(j 1 i) |
||
(print "*")) |
(print "*")) |
||
(print "\n")) |
(print "\n")) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="python">for i in 1..5: |
||
for j in 1..i: |
for j in 1..i: |
||
stdout.write("*") |
stdout.write("*") |
||
echo("")</ |
echo("")</syntaxhighlight> |
||
=={{header|NS-HUBASIC}}== |
=={{header|NS-HUBASIC}}== |
||
< |
<syntaxhighlight lang="ns-hubasuc">10 FOR I=1 TO 5 |
||
20 FOR J=1 TO I |
20 FOR J=1 TO I |
||
30 PRINT "*"; |
30 PRINT "*"; |
||
40 NEXT |
40 NEXT |
||
50 PRINT |
50 PRINT |
||
60 NEXT</ |
60 NEXT</syntaxhighlight> |
||
=={{header|Nu}}== |
|||
<syntaxhighlight lang="nu"> |
|||
for i in 1..5 { |
|||
for j in 1..$i { |
|||
print -n "*" |
|||
} |
|||
print "" |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
Works with oo2c Version 2 |
Works with oo2c Version 2 |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE LoopFor; |
MODULE LoopFor; |
||
IMPORT |
IMPORT |
||
Line 2,393: | Line 2,852: | ||
END |
END |
||
END LoopFor. |
END LoopFor. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class For { |
class For { |
||
Line 2,413: | Line 2,872: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">for i = 1 to 5 do |
||
for j = 1 to i do |
for j = 1 to i do |
||
print_string "*" |
print_string "*" |
||
done; |
done; |
||
print_newline () |
print_newline () |
||
done</ |
done</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">for i = 0:1:4 |
||
for j = 0:1:i |
for j = 0:1:i |
||
printf("*"); |
printf("*"); |
||
endfor |
endfor |
||
printf("\n"); |
printf("\n"); |
||
endfor</ |
endfor</syntaxhighlight> |
||
=={{header|Odin}}== |
|||
<syntaxhighlight lang="odin"> |
|||
package main |
|||
import "core:fmt" |
|||
main :: proc() { |
|||
for i := 1 ; i <= 5 ; i += 1 { |
|||
for j := 1; j <= i; j += 1 { |
|||
fmt.printf("*") |
|||
} |
|||
fmt.println() |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: loopFor(n) |
||
| i j | |
| i j | |
||
n loop: i [ |
n loop: i [ |
||
i loop: j [ "*" print ] |
i loop: j [ "*" print ] |
||
printcr ;</ |
printcr ;</syntaxhighlight> |
||
=={{header|Onyx}}== |
=={{header|Onyx}}== |
||
< |
<syntaxhighlight lang="onyx">1 1 5 {dup {`*'} repeat bdup bpop ncat `\n' cat print} for flush</syntaxhighlight> |
||
Using repeat inside the for loop instead of nesting another for loop is shorter and more efficient. |
Using repeat inside the for loop instead of nesting another for loop is shorter and more efficient. |
||
=={{header|Order}}== |
=={{header|Order}}== |
||
< |
<syntaxhighlight lang="c">#include <order/interpreter.h> |
||
ORDER_PP( |
ORDER_PP( |
||
Line 2,452: | Line 2,926: | ||
8space)), |
8space)), |
||
1, 6) |
1, 6) |
||
)</ |
)</syntaxhighlight> |
||
(Order cannot print newlines, so this example just uses a space.) |
(Order cannot print newlines, so this example just uses a space.) |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">for I in 1..5 do |
||
for _ in 1..I do |
for _ in 1..I do |
||
{System.printInfo "*"} |
{System.printInfo "*"} |
||
end |
end |
||
{System.showInfo ""} |
{System.showInfo ""} |
||
end</ |
end</syntaxhighlight> |
||
Note: we don't use the inner loop variable, so we prefer not to give it a name. |
Note: we don't use the inner loop variable, so we prefer not to give it a name. |
||
=={{header|Panoramic}}== |
=={{header|Panoramic}}== |
||
<syntaxhighlight lang="panoramic"> |
|||
<lang Panoramic> |
|||
dim x,y |
dim x,y |
||
Line 2,479: | Line 2,953: | ||
next x |
next x |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">for(a=1,5,for(b=1,a,print1("*"));print())</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">program stars(output); |
||
var |
var |
||
Line 2,497: | Line 2,971: | ||
writeln |
writeln |
||
end |
end |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
## |
|||
for var i:=1 to 5 do |
|||
begin |
|||
for var j:=1 to i do |
|||
Write('*'); |
|||
Writeln |
|||
end; |
|||
</syntaxhighlight> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">for(my $x = 1; $x <= 5; $x++) { |
||
for(my $y = 1; $y <= $x; $y++) { |
for(my $y = 1; $y <= $x; $y++) { |
||
print "*"; |
print "*"; |
||
} |
} |
||
print "\n"; |
print "\n"; |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="perl">foreach (1..5) { |
||
foreach (1..$_) { |
foreach (1..$_) { |
||
print '*'; |
print '*'; |
||
} |
} |
||
print "\n"; |
print "\n"; |
||
}</ |
}</syntaxhighlight> |
||
However, if we lift the constraint of two loops the code will be simpler: |
However, if we lift the constraint of two loops the code will be simpler: |
||
< |
<syntaxhighlight lang="perl">print ('*' x $_ . "\n") for 1..5;</syntaxhighlight> |
||
or equivalently |
or equivalently |
||
< |
<syntaxhighlight lang="perl">map {print '*' x $_ . "\n"} 1..5;</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--<syntaxhighlight lang="phix">--> |
|||
<lang Phix>for i=1 to 5 do |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">do</span> |
|||
for j=1 to i do |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">i</span> <span style="color: #008080;">do</span> |
|||
puts(1,"*") |
|||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"*"</span><span style="color: #0000FF;">)</span> |
|||
end for |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
puts(1,"\n") |
|||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span> |
|||
end for</lang> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<!--</syntaxhighlight>--> |
|||
=={{header|Phixmonti}}== |
|||
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/Loops/For |
|||
by Galileo, 11/2022 #/ |
|||
include ..\Utilitys.pmt |
|||
5 for |
|||
for |
|||
"*" print |
|||
endfor |
|||
nl |
|||
endfor |
|||
5 for '*' swap repeat ? endfor</syntaxhighlight> |
|||
{{out}} |
|||
<pre>* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
=== Press any key to exit ===</pre> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">for ($i = 1; $i <= 5; $i++) { |
||
for ($j = 1; $j <= $i; $j++) { |
for ($j = 1; $j <= $i; $j++) { |
||
echo '*'; |
echo '*'; |
||
} |
} |
||
echo "\n"; |
echo "\n"; |
||
}</ |
}</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="php">foreach (range(1, 5) as $i) { |
||
foreach (range(1, $i) as $j) { |
foreach (range(1, $i) as $j) { |
||
echo '*'; |
echo '*'; |
||
} |
} |
||
echo "\n"; |
echo "\n"; |
||
}</ |
}</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="php">foreach (range(1, 5) as $i) |
||
echo str_repeat('*', $i) , PHP_EOL;</ |
echo str_repeat('*', $i) , PHP_EOL;</syntaxhighlight> |
||
=={{header|Picat}}== |
|||
<syntaxhighlight lang="picat">go => |
|||
N = 5, |
|||
foreach(I in 1..N) |
|||
foreach(_J in 1..I) |
|||
print("*") |
|||
end, |
|||
nl |
|||
end.</syntaxhighlight> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(for N 5 |
||
(do N (prin "*")) |
(do N (prin "*")) |
||
(prinl) )</ |
(prinl) )</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike">int main(){ |
||
for(int i = 1; i <= 5; i++){ |
for(int i = 1; i <= 5; i++){ |
||
for(int j=1; j <= i; j++){ |
for(int j=1; j <= i; j++){ |
||
Line 2,560: | Line 3,086: | ||
write("\n"); |
write("\n"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PILOT}}== |
=={{header|PILOT}}== |
||
Core PILOT does not offer any way of printing without a newline, so in the inner loop we concatenate another star onto the string variable <code>$stars</code> each time round and then print it in the outer loop. |
Core PILOT does not offer any way of printing without a newline, so in the inner loop we concatenate another star onto the string variable <code>$stars</code> each time round and then print it in the outer loop. |
||
< |
<syntaxhighlight lang="pilot">C :i = 1 |
||
*OuterLoop |
*OuterLoop |
||
C :j = 0 |
C :j = 0 |
||
Line 2,575: | Line 3,101: | ||
C :i = i + 1 |
C :i = i + 1 |
||
J ( i < 6 ) :*OuterLoop |
J ( i < 6 ) :*OuterLoop |
||
END:</ |
END:</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
Basic version: |
Basic version: |
||
< |
<syntaxhighlight lang="pl/i">do i = 1 to 5; |
||
do j = 1 to i; |
do j = 1 to i; |
||
put edit ('*') (a); |
put edit ('*') (a); |
||
end; |
end; |
||
put skip; |
put skip; |
||
end;</ |
end;</syntaxhighlight> |
||
Advanced version: |
Advanced version: |
||
< |
<syntaxhighlight lang="pl/i">do i = 1 to 5; |
||
put skip edit (('*' do j = 1 to i)) (a); |
put skip edit (('*' do j = 1 to i)) (a); |
||
end;</ |
end;</syntaxhighlight> |
||
Due to the new line requirement a mono line version is not possible |
Due to the new line requirement a mono line version is not possible |
||
< |
<syntaxhighlight lang="pl/i">put edit ((('*' do j = 1 to i)do i=1 to 5))(a); /* no new line */</syntaxhighlight> |
||
=={{header|Plain English}}== |
=={{header|Plain English}}== |
||
Plain English doesn't allow the direct nesting of loops. Instead, you are encouraged to make one routine for each loop and let the routine headers describe what the loops are doing. |
Plain English doesn't allow the direct nesting of loops. Instead, you are encouraged to make one routine for each loop and let the routine headers describe what the loops are doing. |
||
< |
<syntaxhighlight lang="plainenglish">To run: |
||
Start up. |
Start up. |
||
Write a triangle of asterisks on the console given 5. |
Write a triangle of asterisks on the console given 5. |
||
Line 2,608: | Line 3,134: | ||
If a counter is past the size, exit. |
If a counter is past the size, exit. |
||
Write a row of asterisks on the console given the counter. |
Write a row of asterisks on the console given the counter. |
||
Repeat.</ |
Repeat.</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">lvars i, j; |
||
for i from 1 to 5 do |
for i from 1 to 5 do |
||
for j from 1 to i do |
for j from 1 to i do |
||
Line 2,617: | Line 3,143: | ||
endfor; |
endfor; |
||
printf('\n') |
printf('\n') |
||
endfor;</ |
endfor;</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">for ($i = 1; $i -le 5; $i++) { |
||
for ($j = 1; $j -le $i; $j++) { |
for ($j = 1; $j -le $i; $j++) { |
||
Write-Host -NoNewline * |
Write-Host -NoNewline * |
||
} |
} |
||
Write-Host |
Write-Host |
||
}</ |
}</syntaxhighlight> |
||
Alternatively the same can be achieved with a slightly different way by using the range operator along with the <code>ForEach-Object</code> cmdlet: |
Alternatively the same can be achieved with a slightly different way by using the range operator along with the <code>ForEach-Object</code> cmdlet: |
||
< |
<syntaxhighlight lang="powershell">1..5 | ForEach-Object { |
||
1..$_ | ForEach-Object { |
1..$_ | ForEach-Object { |
||
Write-Host -NoNewline * |
Write-Host -NoNewline * |
||
} |
} |
||
Write-Host |
Write-Host |
||
}</ |
}</syntaxhighlight> |
||
while the inner loop wouldn't strictly be necessary and can be replaced with simply <code>"*" * $_</code>. |
while the inner loop wouldn't strictly be necessary and can be replaced with simply <code>"*" * $_</code>. |
||
=={{header|Processing}}== |
=={{header|Processing}}== |
||
< |
<syntaxhighlight lang="java">size( 105,120 ); |
||
for ( int i=20; i<=100; i+=20 ) |
for ( int i=20; i<=100; i+=20 ) |
||
for ( int j=10; j<=i; j+=20 ) |
for ( int j=10; j<=i; j+=20 ) |
||
text( "*", j,i );</ |
text( "*", j,i );</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Prolog has a built in iterator, between(Lo,Hi,I) which binds the value of I to successive values from Lo to Hi. This is the closest thing Prolog has to a 'for' loop. |
Prolog has a built in iterator, between(Lo,Hi,I) which binds the value of I to successive values from Lo to Hi. This is the closest thing Prolog has to a 'for' loop. |
||
< |
<syntaxhighlight lang="prolog">example :- |
||
between(1,5,I), nl, between(1,I,_J), |
between(1,5,I), nl, between(1,I,_J), |
||
write('*'), fail. |
write('*'), fail. |
||
example.</ |
example.</syntaxhighlight> |
||
<pre>?- example. |
<pre>?- example. |
||
Line 2,658: | Line 3,184: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">import sys |
||
for i in xrange(5): |
for i in xrange(5): |
||
for j in xrange(i+1): |
for j in xrange(i+1): |
||
sys.stdout.write("*") |
sys.stdout.write("*") |
||
print</ |
print</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="python">for i in range(1,6): |
||
print '*' * i</ |
print '*' * i</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="python">print('\n'.join('*' * i for i in range(1, 6)))</syntaxhighlight> |
||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
''CBTJD'': 2020/03/14 |
''CBTJD'': 2020/03/14 |
||
< |
<syntaxhighlight lang="qbasic">FOR c = 1 TO 5 |
||
FOR n = 1 TO c |
FOR n = 1 TO c |
||
PRINT "*"; |
PRINT "*"; |
||
NEXT |
NEXT |
||
PRINT |
PRINT |
||
NEXT</ |
NEXT</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery">5 times [ i^ 1+ times [ say "*" ] cr ]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>* |
<pre>* |
||
Line 2,689: | Line 3,215: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">for(i in 0:4) { |
||
s <- "" |
s <- "" |
||
for(j in 0:i) { |
for(j in 0:i) { |
||
Line 2,695: | Line 3,221: | ||
} |
} |
||
print(s) |
print(s) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">(for ([i (in-range 1 6)]) (for ([j i]) (display "*")) (newline))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 2,704: | Line 3,230: | ||
{{works with|Rakudo|#22 "Thousand Oaks"}} |
{{works with|Rakudo|#22 "Thousand Oaks"}} |
||
<lang |
<syntaxhighlight lang="raku" line>for ^5 { |
||
for 0..$_ { |
for 0..$_ { |
||
Line 2,712: | Line 3,238: | ||
print "\n"; |
print "\n"; |
||
}</ |
}</syntaxhighlight> |
||
or using only one for loop: |
or using only one for loop: |
||
<lang |
<syntaxhighlight lang="raku" line>say '*' x $_ for 1..5;</syntaxhighlight> |
||
or without using any loops at all: |
or without using any loops at all: |
||
<lang |
<syntaxhighlight lang="raku" line>([\~] "*" xx 5).join("\n").say;</syntaxhighlight> |
||
=={{header|Rapira}}== |
|||
<syntaxhighlight lang="rapira">for N from 1 to 5 do |
|||
output: "*" * N |
|||
od</syntaxhighlight> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">; Use 'repeat' when an index required, 'loop' when repetition suffices: |
||
repeat i 5 [ |
repeat i 5 [ |
||
Line 2,735: | Line 3,266: | ||
loop i [prin "*"] |
loop i [prin "*"] |
||
print "" |
print "" |
||
]</ |
]</syntaxhighlight> |
||
=={{header|Red}}== |
|||
<syntaxhighlight lang="rebol">Red[] |
|||
repeat i 5 [ |
|||
loop i [prin "*"] |
|||
prin newline |
|||
]</syntaxhighlight> |
|||
=={{header|ReScript}}== |
|||
<syntaxhighlight lang="rescript">let s = ref("") |
|||
for i in 1 to 5 { |
|||
for _ in 1 to i { |
|||
s := Js.String2.concat(s.contents, "*") |
|||
} |
|||
s := Js.String2.concat(s.contents, "\n") |
|||
} |
|||
Js.log(s.contents)</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
bsc for.res > for.js |
|||
node for.js |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
</pre> |
|||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">6 [ 0; cr [ '* emit ] times ] iter</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===using concatenation=== |
===using concatenation=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates an outer DO loop controlling the inner DO loop with a "FOR".*/ |
||
do j=1 for 5 /*this is the same as: do j=1 to 5 */ |
do j=1 for 5 /*this is the same as: do j=1 to 5 */ |
||
Line 2,750: | Line 3,309: | ||
end /*k*/ |
end /*k*/ |
||
say $ /*display character string being built.*/ |
say $ /*display character string being built.*/ |
||
end /*j*/ /*stick a fork in it, we're all done. */</ |
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
{{out|output|:}} |
{{out|output|:}} |
||
<pre> |
<pre> |
||
Line 2,761: | Line 3,320: | ||
===using abutment=== |
===using abutment=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates an outer DO loop controlling the inner DO loop with a "FOR".*/ |
||
do j=1 for 5 /*this is the same as: do j=1 to 5 */ |
do j=1 for 5 /*this is the same as: do j=1 to 5 */ |
||
Line 2,769: | Line 3,328: | ||
end /*k*/ |
end /*k*/ |
||
say $ /*display character string being built.*/ |
say $ /*display character string being built.*/ |
||
end /*j*/ /*stick a fork in it, we're all done. */</ |
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br> |
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
can be done in just one line: |
can be done in just one line: |
||
< |
<syntaxhighlight lang="ring"> |
||
for i = 1 to 5 for x = 1 to i see "*" next see nl next |
for i = 1 to 5 for x = 1 to i see "*" next see nl next |
||
</syntaxhighlight> |
|||
</lang> |
|||
or multiple line |
or multiple line |
||
< |
<syntaxhighlight lang="ring"> |
||
for i = 1 to 5 |
for i = 1 to 5 |
||
for x = 1 to i |
for x = 1 to i |
||
Line 2,785: | Line 3,344: | ||
see nl |
see nl |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
RPL provides two types of counting loops: <code>FOR</code>..<code>NEXT</code> and <code>START</code>..<code>NEXT</code>, the latter looping without providing access to its counter. |
|||
≪ 1 5 '''FOR''' j |
|||
"" |
|||
1 j '''START''' |
|||
"*" + |
|||
'''NEXT |
|||
NEXT''' |
|||
≫ |
|||
'LOOPS' STO |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
One can write a <tt>for</tt> loop as <tt>for i in 1..5; ...end</tt> or as <tt>for i in 1..5 do ... end</tt> or as <tt>(1..5).each do |i| ... end</tt>. All three forms call <tt>Range#each</tt> to iterate <tt>1..5</tt>. |
One can write a <tt>for</tt> loop as <tt>for i in 1..5; ...end</tt> or as <tt>for i in 1..5 do ... end</tt> or as <tt>(1..5).each do |i| ... end</tt>. All three forms call <tt>Range#each</tt> to iterate <tt>1..5</tt>. |
||
Line 2,795: | Line 3,364: | ||
|- |
|- |
||
| style="vertical-align: top;" | |
| style="vertical-align: top;" | |
||
< |
<syntaxhighlight lang="ruby">for i in 1..5 |
||
for j in 1..i |
for j in 1..i |
||
print "*" |
print "*" |
||
end |
end |
||
puts |
puts |
||
end</ |
end</syntaxhighlight> |
||
| style="vertical-align: top;" | |
| style="vertical-align: top;" | |
||
< |
<syntaxhighlight lang="ruby">(1..5).each do |i| |
||
(1..i).each do |j| |
(1..i).each do |j| |
||
print "*" |
print "*" |
||
end |
end |
||
puts |
puts |
||
end</ |
end</syntaxhighlight> |
||
|} |
|} |
||
Line 2,818: | Line 3,387: | ||
|- |
|- |
||
| style="vertical-align: top;" | |
| style="vertical-align: top;" | |
||
< |
<syntaxhighlight lang="ruby">1.upto(5) do |i| |
||
1.upto(i) do |j| |
1.upto(i) do |j| |
||
print "*" |
print "*" |
||
end |
end |
||
puts |
puts |
||
end</ |
end</syntaxhighlight> |
||
| style="vertical-align: top;" | |
| style="vertical-align: top;" | |
||
< |
<syntaxhighlight lang="ruby">5.times do |i| |
||
# i goes from 0 to 4 |
# i goes from 0 to 4 |
||
(i+1).times do |
(i+1).times do |
||
Line 2,831: | Line 3,400: | ||
end |
end |
||
puts |
puts |
||
end</ |
end</syntaxhighlight> |
||
| style="vertical-align: top;" | |
| style="vertical-align: top;" | |
||
< |
<syntaxhighlight lang="ruby">i = 1 |
||
loop do |
loop do |
||
j = 1 |
j = 1 |
||
Line 2,842: | Line 3,411: | ||
puts |
puts |
||
break if (i += 1) > 5 |
break if (i += 1) > 5 |
||
end</ |
end</syntaxhighlight> |
||
|} |
|} |
||
Or we can use String#* as the inner loop, and Enumerable#map as the outer loop. This shrinks the program to one line. |
Or we can use String#* as the inner loop, and Enumerable#map as the outer loop. This shrinks the program to one line. |
||
< |
<syntaxhighlight lang="ruby">puts (1..5).map { |i| "*" * i }</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
The compiler warns when you create an unused variable; here we use _ to avoid this effect. |
The compiler warns when you create an unused variable; here we use _ to avoid this effect. |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
for i in 0..5 { |
for i in 0..5 { |
||
for _ in 0..=i { |
for _ in 0..=i { |
||
Line 2,859: | Line 3,428: | ||
println!(); |
println!(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Salmon}}== |
=={{header|Salmon}}== |
||
< |
<syntaxhighlight lang="salmon">iterate (x; [0...4]) |
||
{ |
{ |
||
iterate (y; [0...x]) |
iterate (y; [0...x]) |
||
print("*");; |
print("*");; |
||
print("\n"); |
print("\n"); |
||
};</ |
};</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="salmon">for (x; 0; x < 5) |
||
{ |
{ |
||
for (y; 0; y <= x) |
for (y; 0; y <= x) |
||
print("*");; |
print("*");; |
||
print("\n"); |
print("\n"); |
||
};</ |
};</syntaxhighlight> |
||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
< |
<syntaxhighlight lang="sas">data _null_; |
||
length a $5; |
length a $5; |
||
do n=1 to 5; |
do n=1 to 5; |
||
Line 2,899: | Line 3,468: | ||
put a; |
put a; |
||
end; |
end; |
||
run;</ |
run;</syntaxhighlight> |
||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
Line 2,905: | Line 3,474: | ||
Sather allows the definition of new iterators. Here's we define <code>for!</code> so that it resembles the known <code>for</code> in other languages, even though the <code>upto!</code> built-in can be used. |
Sather allows the definition of new iterators. Here's we define <code>for!</code> so that it resembles the known <code>for</code> in other languages, even though the <code>upto!</code> built-in can be used. |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
-- from, to, step |
-- from, to, step |
||
for!(once init:INT, once to:INT, once inc:INT):INT is |
for!(once init:INT, once to:INT, once inc:INT):INT is |
||
Line 2,925: | Line 3,494: | ||
end; |
end; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">for (i <- 1 to 5) { |
||
for (j <- 1 to i) |
for (j <- 1 to i) |
||
print("*") |
print("*") |
||
println() |
println() |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(do ((i 1 (+ i 1))) |
||
((> i 5)) |
((> i 5)) |
||
(do ((j 1 (+ j 1))) |
(do ((j 1 (+ j 1))) |
||
((> j i)) |
((> j i)) |
||
(display "*")) |
(display "*")) |
||
(newline))</ |
(newline))</syntaxhighlight> |
||
=={{header|Scilab}}== |
=={{header|Scilab}}== |
||
{{works with|Scilab|5.5.1}} |
{{works with|Scilab|5.5.1}} |
||
<lang>for i=1:5 |
<syntaxhighlight lang="text">for i=1:5 |
||
s="" |
s="" |
||
for j=1:i |
for j=1:i |
||
Line 2,950: | Line 3,519: | ||
end |
end |
||
printf("%s\n",s) |
printf("%s\n",s) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>* |
<pre>* |
||
Line 2,959: | Line 3,528: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
<syntaxhighlight lang="python"> |
|||
<lang seed7>for I range 1 to 5 do |
|||
$ include "seed7_05.s7i"; |
|||
for J range 1 to I do |
|||
write("*"); |
|||
const proc: main is func |
|||
end for; |
|||
local |
|||
writeln; |
|||
var integer: I is 1; |
|||
end for;</lang> |
|||
var integer: J is 1; |
|||
begin |
|||
for I range 1 to 5 do |
|||
for J range 1 to I do |
|||
write("*"); |
|||
end for; |
|||
writeln; |
|||
end for; |
|||
end func; |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
</pre> |
|||
=={{header|SETL}}== |
=={{header|SETL}}== |
||
< |
<syntaxhighlight lang="ada">for i in {1..5} loop |
||
for j in {1..i} loop |
for j in {1..i} loop |
||
nprint( '*' ); |
nprint( '*' ); |
||
end loop; |
end loop; |
||
print; -- new line |
print; -- new line |
||
end loop;</ |
end loop;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
'''for(;;)''' loop: |
'''for(;;)''' loop: |
||
< |
<syntaxhighlight lang="ruby">for (var i = 1; i <= 5; i++) { |
||
for (var j = 1; j <= i; j++) { |
for (var j = 1; j <= i; j++) { |
||
print '*' |
print '*' |
||
} |
} |
||
print "\n" |
print "\n" |
||
}</ |
}</syntaxhighlight> |
||
'''for([])''' loop: |
'''for([])''' loop: |
||
< |
<syntaxhighlight lang="ruby">for (1..5) { |i| |
||
for (1..i) { print '*' } |
for (1..i) { print '*' } |
||
print "\n" |
print "\n" |
||
}</ |
}</syntaxhighlight> |
||
'''for-in''' loop: |
'''for-in''' loop: |
||
< |
<syntaxhighlight lang="ruby">for i in (1..5) { |
||
for j in (1..i) { print '*' } |
for j in (1..i) { print '*' } |
||
print "\n" |
print "\n" |
||
}</ |
}</syntaxhighlight> |
||
Idiomatic: |
Idiomatic: |
||
< |
<syntaxhighlight lang="ruby">5.times { |i| |
||
i.times { print '*' } |
i.times { print '*' } |
||
print "\n" |
print "\n" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Simula}}== |
=={{header|Simula}}== |
||
{{works with|SIMULA-67}} |
{{works with|SIMULA-67}} |
||
< |
<syntaxhighlight lang="simula">begin |
||
integer i,j; |
integer i,j; |
||
for i:=1 step 1 until 5 do |
for i:=1 step 1 until 5 do |
||
Line 3,012: | Line 3,600: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">1 to: 5 do: [| :n | inform: ($* repeatedTimes: n)].</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">1 to: 5 do: [ :aNumber | |
||
aNumber timesRepeat: [ '*' display ]. |
aNumber timesRepeat: [ '*' display ]. |
||
Character nl display. |
Character nl display. |
||
]</ |
]</syntaxhighlight> |
||
or: |
or: |
||
< |
<syntaxhighlight lang="smalltalk">1 to: 5 do: [ :row | |
||
1 to: row do: [:col | '*' display ]. |
1 to: row do: [:col | '*' display ]. |
||
]</ |
]</syntaxhighlight> |
||
(only for demonstration of nested for-loops; as the column is not needed, the first solution is probably clearer). |
(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: |
However, streams already have some builtin repetition mechanism, so a programmer might write: |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
< |
<syntaxhighlight lang="smalltalk">1 to: 5 do: [ :n | |
||
Stdout next: n put: $*; cr |
Stdout next: n put: $*; cr |
||
]</ |
]</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
A slightly longer, "mundane" version |
A slightly longer, "mundane" version |
||
< |
<syntaxhighlight lang="snobol">ol outer = ?lt(outer,5) outer + 1 :f(end) |
||
inner = outer; stars = "" |
inner = outer; stars = "" |
||
il stars = ?gt(inner,0) stars "*" :f(disp) |
il stars = ?gt(inner,0) stars "*" :f(disp) |
||
inner = inner - 1 :(il) |
inner = inner - 1 :(il) |
||
disp output = stars; :(ol) |
disp output = stars; :(ol) |
||
end</ |
end</syntaxhighlight> |
||
The "real SNOBOL4" starts here: |
The "real SNOBOL4" starts here: |
||
< |
<syntaxhighlight lang="snobol">outer b = a = ?lt(a,5) a + 1 :f(end) |
||
inner t = t ?(b = (gt(b,0) b - 1)) "*" :s(inner) |
inner t = t ?(b = (gt(b,0) b - 1)) "*" :s(inner) |
||
t span("*") . terminal = :(outer) |
t span("*") . terminal = :(outer) |
||
end</ |
end</syntaxhighlight> |
||
one "loop" only: |
one "loop" only: |
||
< |
<syntaxhighlight lang="snobol"> a = "*****"; |
||
a a len(x = x + 1) . output :s(a) |
a a len(x = x + 1) . output :s(a) |
||
end</ |
end</syntaxhighlight> |
||
... or just (courtesy of GEP2): |
... or just (courtesy of GEP2): |
||
{{works with|SNOBOL4|which defaults to anchored mode}} |
{{works with|SNOBOL4|which defaults to anchored mode}} |
||
< |
<syntaxhighlight lang="snobol"> "*****" arb $ output fail |
||
end</ |
end</syntaxhighlight> |
||
=={{header|SNUSP}}== |
=={{header|SNUSP}}== |
||
Line 3,093: | Line 3,681: | ||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
< |
<syntaxhighlight lang="sparkling">for (var row = 1; row <= 5; row++) { |
||
for (var col = 1; col <= row; col++) { |
for (var col = 1; col <= row; col++) { |
||
printf("*"); |
printf("*"); |
||
Line 3,099: | Line 3,687: | ||
print(); |
print(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Spin}}== |
=={{header|Spin}}== |
||
Line 3,106: | Line 3,694: | ||
{{works with|HomeSpun}} |
{{works with|HomeSpun}} |
||
{{works with|OpenSpin}} |
{{works with|OpenSpin}} |
||
< |
<syntaxhighlight lang="spin">con |
||
_clkmode = xtal1 + pll16x |
_clkmode = xtal1 + pll16x |
||
_clkfreq = 80_000_000 |
_clkfreq = 80_000_000 |
||
Line 3,123: | Line 3,711: | ||
waitcnt(_clkfreq + cnt) |
waitcnt(_clkfreq + cnt) |
||
ser.stop |
ser.stop |
||
cogstop(0)</ |
cogstop(0)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,134: | Line 3,722: | ||
=={{header|SPL}}== |
=={{header|SPL}}== |
||
< |
<syntaxhighlight lang="spl">> i, 1..5 |
||
> j, 1..i |
> j, 1..i |
||
#.output("*",#.rs) |
#.output("*",#.rs) |
||
< |
< |
||
#.output() |
#.output() |
||
<</ |
<</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">forvalues n=1/5 { |
||
local s "" |
local s "" |
||
forvalues i=1/`n' { |
forvalues i=1/`n' { |
||
Line 3,149: | Line 3,737: | ||
} |
} |
||
display "`s'" |
display "`s'" |
||
}</ |
}</syntaxhighlight> |
||
=== Mata === |
=== Mata === |
||
< |
<syntaxhighlight lang="stata">for (i=1; i<=5; i++) { |
||
for (j=1; j<=i; j++) printf("*") |
for (j=1; j<=i; j++) printf("*") |
||
printf("\n") |
printf("\n") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Suneido}}== |
=={{header|Suneido}}== |
||
< |
<syntaxhighlight lang="suneido">for(i = 0; i < 5; ++i) |
||
{ |
{ |
||
str = '' |
str = '' |
||
Line 3,164: | Line 3,752: | ||
str $= '*' |
str $= '*' |
||
Print(str) |
Print(str) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">for i in 1...5 { |
||
for _ in 1...i { |
for _ in 1...i { |
||
print("*", terminator: "") |
print("*", terminator: "") |
||
} |
} |
||
print() |
print() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,184: | Line 3,772: | ||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
Tailspin uses streams of values within streams of values rather than loops. |
Tailspin uses streams of values within streams of values rather than loops. |
||
< |
<syntaxhighlight lang="tailspin"> |
||
1..5 -> '$:1..$ -> '*'; |
1..5 -> '$:1..$ -> '*'; |
||
' -> !OUT::write |
' -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,198: | Line 3,786: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">for {set lines 1} {$lines <= 5} {incr lines} { |
||
for {set i 1} {$i <= $lines} {incr i} { |
for {set i 1} {$i <= $lines} {incr i} { |
||
puts -nonewline "*" |
puts -nonewline "*" |
||
} |
} |
||
puts "" |
puts "" |
||
}</ |
}</syntaxhighlight> |
||
Note that it would be more normal to produce this output with: |
Note that it would be more normal to produce this output with: |
||
< |
<syntaxhighlight lang="tcl">for {set i 1} {$i <= 5} {incr i} { |
||
puts [string repeat "*" $i] |
puts [string repeat "*" $i] |
||
}</ |
}</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="tcl">set line "" |
||
for { set io [open test.txt r] } { ![eof $io] } { gets $io line } { |
for { set io [open test.txt r] } { ![eof $io] } { gets $io line } { |
||
if { $line != "" } { ...do something here... } |
if { $line != "" } { ...do something here... } |
||
}</ |
}</syntaxhighlight> |
||
(This is a somewhat awkward example; just to show what is possible) |
(This is a somewhat awkward example; just to show what is possible) |
||
Line 3,229: | Line 3,817: | ||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
< |
<syntaxhighlight lang="ti89b">Local i,j |
||
ClrIO |
ClrIO |
||
For i, 1, 5 |
For i, 1, 5 |
||
Line 3,235: | Line 3,823: | ||
Output i*8, j*6, "*" |
Output i*8, j*6, "*" |
||
EndFor |
EndFor |
||
EndFor</ |
EndFor</syntaxhighlight> |
||
=={{header|TorqueScript}}== |
=={{header|TorqueScript}}== |
||
< |
<syntaxhighlight lang="torque">for(%i = 0; %i < 5; %i++) |
||
{ |
{ |
||
for(%x = %i; %x < 5; %x++) |
for(%x = %i; %x < 5; %x++) |
||
Line 3,246: | Line 3,834: | ||
echo(%string); |
echo(%string); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TransFORTH}}== |
=={{header|TransFORTH}}== |
||
< |
<syntaxhighlight lang="forth">: PRINTSTARS ( ROWS -- ) |
||
1 + 1 DO |
1 + 1 DO |
||
I 0 DO |
I 0 DO |
||
PRINT " * " LOOP |
PRINT " * " LOOP |
||
CR LOOP ; |
CR LOOP ; |
||
5 PRINTSTARS</ |
5 PRINTSTARS</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
m="" |
m="" |
||
Line 3,264: | Line 3,852: | ||
PRINT m |
PRINT m |
||
ENDLOOP |
ENDLOOP |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,275: | Line 3,863: | ||
=={{header|TypeScript}}== |
=={{header|TypeScript}}== |
||
< |
<syntaxhighlight lang="javascript">for (let i: number = 0; i < 5; ++i) { |
||
let line: string = "" |
let line: string = "" |
||
for(let j: number = 0; j <= i; ++j) { |
for(let j: number = 0; j <= i; ++j) { |
||
Line 3,282: | Line 3,870: | ||
console.log(line) |
console.log(line) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
Line 3,288: | Line 3,876: | ||
{{works with|Bourne Shell}} |
{{works with|Bourne Shell}} |
||
< |
<syntaxhighlight lang="bash">#!/bin/sh |
||
# Using a while control construct to emulate a for loop |
# Using a while control construct to emulate a for loop |
||
Line 3,302: | Line 3,890: | ||
echo |
echo |
||
l=`expr "$l" + 1` # Increment the outer counter |
l=`expr "$l" + 1` # Increment the outer counter |
||
done</ |
done</syntaxhighlight> |
||
The [[Bourne Shell]] has a for loop, but it requires a list of words to iterate. |
The [[Bourne Shell]] has a for loop, but it requires a list of words to iterate. |
||
Line 3,309: | Line 3,897: | ||
{{works with|Bourne Shell}} |
{{works with|Bourne Shell}} |
||
{{libheader|jot}} |
{{libheader|jot}} |
||
< |
<syntaxhighlight lang="bash">for i in `jot 5`; do |
||
for j in `jot $i`; do |
for j in `jot $i`; do |
||
printf \* |
printf \* |
||
done |
done |
||
echo |
echo |
||
done</ |
done</syntaxhighlight> |
||
Bash has <tt>for</tt> loops that act like C. These loops are very good for this task. |
Bash has <tt>for</tt> loops that act like C. These loops are very good for this task. |
||
{{works with|Bourne Again SHell|3}} |
{{works with|Bourne Again SHell|3}} |
||
< |
<syntaxhighlight lang="bash">for (( x=1; $x<=5; x=$x+1 )); do |
||
for (( y=1; y<=$x; y=$y+1 )); do |
for (( y=1; y<=$x; y=$y+1 )); do |
||
echo -n '*' |
echo -n '*' |
||
done |
done |
||
echo "" |
echo "" |
||
done</ |
done</syntaxhighlight> |
||
==={{header|C Shell}}=== |
==={{header|C Shell}}=== |
||
{{libheader|jot}} |
{{libheader|jot}} |
||
< |
<syntaxhighlight lang="csh">foreach i (`jot 5`) |
||
foreach j (`jot $i`) |
foreach j (`jot $i`) |
||
echo -n \* |
echo -n \* |
||
end |
end |
||
echo "" |
echo "" |
||
end</ |
end</syntaxhighlight> |
||
==={{header|ksh}}=== |
|||
{{works with|ksh93}} |
|||
<syntaxhighlight lang="ksh">for ((x = 1; x <= 5; x += 1)) |
|||
do |
|||
for ((y = 0; y < x; y += 1)) |
|||
do |
|||
print -n '*' |
|||
done |
|||
print |
|||
done</syntaxhighlight> |
|||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |
||
< |
<syntaxhighlight lang="bash">yes \ | cat -n | (while read n ; do |
||
[ $n -gt 5 ] && exit 0; |
[ $n -gt 5 ] && exit 0; |
||
yes \* | head -n $n | xargs -n $n echo |
yes \* | head -n $n | xargs -n $n echo |
||
done)</ |
done)</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa"># |
||
# for loop |
# for loop |
||
# |
# |
||
Line 3,352: | Line 3,951: | ||
end for |
end for |
||
out endl console |
out endl console |
||
end for</ |
end for</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala">int main (string[] args) { |
||
for (var i = 1; i <= 5; i++) { |
for (var i = 1; i <= 5; i++) { |
||
for (var j = 1; j <= i; j++) { |
for (var j = 1; j <= i; j++) { |
||
Line 3,363: | Line 3,962: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Option Explicit |
||
Sub LoopEx() |
Sub LoopEx() |
||
Dim i As Long, j As Long, s As String |
Dim i As Long, j As Long, s As String |
||
Line 3,376: | Line 3,975: | ||
Debug.Print s |
Debug.Print s |
||
Next |
Next |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">Option Explicit |
||
Dim i, j, s |
Dim i, j, s |
||
For i = 1 To 5 |
For i = 1 To 5 |
||
Line 3,387: | Line 3,986: | ||
Next |
Next |
||
WScript.Echo s |
WScript.Echo s |
||
Next</ |
Next</syntaxhighlight> |
||
=={{header|Vedit macro language}}== |
=={{header|Vedit macro language}}== |
||
< |
<syntaxhighlight lang="vedit">for (#1 = 1; #1 <= 5; #1++) { |
||
for (#2 = 1; #2 <= #1; #2++) { |
for (#2 = 1; #2 <= #1; #2++) { |
||
Type_Char('*') |
Type_Char('*') |
||
} |
} |
||
Type_Newline |
Type_Newline |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Verilog}}== |
|||
<syntaxhighlight lang="verilog"> |
|||
module main; |
|||
integer i, j; |
|||
initial begin |
|||
for(i = 1; i <= 5; i = i + 1) begin |
|||
for(j = 1; j <= i; j = j + 1) $write("*"); |
|||
$display(""); |
|||
end |
|||
$finish ; |
|||
end |
|||
endmodule |
|||
</syntaxhighlight> |
|||
=={{header|Vim Script}}== |
|||
The two-loop approach determined in the description is solved in a similar manner to Python (initial solution) and Nim, using the inbuilt function, [https://vimhelp.org/builtin.txt.html#range%28%29 range()], which technically may be considered a ''for each'' loop. Nonetheless, it is an incrementing integer solution like many others provided. The script will append the output to the end of the current buffer. It uses inbuilt functions [https://vimhelp.org/builtin.txt.html#append%28%29 append()], [https://vimhelp.org/builtin.txt.html#line%28%29 line()], [https://vimhelp.org/builtin.txt.html#setline%28%29 setline()], and [https://vimhelp.org/builtin.txt.html#getline%28%29 getline()]: |
|||
<syntaxhighlight lang="vim"> |
|||
for i in range(1, 5) |
|||
call append(line('$'), '') |
|||
for j in range(1, i) |
|||
call setline(line('$'), getline('$') .. '*') |
|||
endfor |
|||
endfor |
|||
</syntaxhighlight> |
|||
If the constraint to use two ''for'' loops was absent, the more concise Vim Script solution ― ''similar to idiomatic Python solution #2'' ― would be (this time using builtin functions [https://vimhelp.org/eval.txt.html#%3Aechoconsole echoc[onsole<nowiki>]</nowiki>] and [https://vimhelp.org/builtin.txt.html#repeat%28%29 repeat()] to demonstrate another approach to generating the output, i.e., to the console): |
|||
<syntaxhighlight lang="vim"> |
|||
for i in range(1, 5) |
|||
echoc repeat('*', i) |
|||
endfor |
|||
</syntaxhighlight> |
|||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="v (vlang)">fn main() { |
|||
for i in 1..6 { |
|||
for _ in 1..i+1 { |
|||
print("*") |
|||
} |
|||
print("\n") |
|||
} |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
</pre> |
|||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="wart">for i 1 (i <= 5) ++i |
||
for j 0 (j < i) ++j |
for j 0 (j < i) ++j |
||
pr "*" |
pr "*" |
||
(prn)</ |
(prn)</syntaxhighlight> |
||
=={{header|Wee Basic}}== |
=={{header|Wee Basic}}== |
||
print 1 "" ensures the end of program text is separate from the asterisk characters. |
print 1 "" ensures the end of program text is separate from the asterisk characters. |
||
< |
<syntaxhighlight lang="wee basic">for y=0 to 4 |
||
print 1 "" |
print 1 "" |
||
for x=0 to y |
for x=0 to y |
||
Line 3,411: | Line 4,066: | ||
next |
next |
||
next |
next |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="wren">for (i in 1..5) { |
||
for (j in 1..i) System.write("*") |
for (j in 1..i) System.write("*") |
||
System.print() |
System.print() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,430: | Line 4,085: | ||
=={{header|x86 Assembly}}== |
=={{header|x86 Assembly}}== |
||
This subroutine uses only the original 16-bit 8086 instruction set; it is written for DOS, but could be adapted to run under other operating systems. |
This subroutine uses only the original 16-bit 8086 instruction set; it is written for DOS, but could be adapted to run under other operating systems. |
||
< |
<syntaxhighlight lang="x86asm">loops: mov bx, 1 ; outer loop counter |
||
outerloop: mov cx, bx ; inner loop counter |
outerloop: mov cx, bx ; inner loop counter |
||
Line 3,450: | Line 4,105: | ||
jne outerloop |
jne outerloop |
||
ret</ |
ret</syntaxhighlight> |
||
=={{header|XBasic}}== |
=={{header|XBasic}}== |
||
{{works with|Windows XBasic}} |
{{works with|Windows XBasic}} |
||
< |
<syntaxhighlight lang="xbasic"> |
||
PROGRAM "for" |
PROGRAM "for" |
||
Line 3,468: | Line 4,123: | ||
END FUNCTION |
END FUNCTION |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|XBS}}== |
|||
<syntaxhighlight lang="xbs">const repChar:string = "*"; |
|||
const maxIters = 5; |
|||
for(i=1;maxIters;1){ |
|||
set str:string = ""; |
|||
for(o=1;i;1){ |
|||
str+=repChar; |
|||
} |
|||
log(str); |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>* |
|||
** |
|||
*** |
|||
**** |
|||
*****</pre> |
|||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
The equivalent of other languages' <tt>FOR</tt> or <tt>DO</tt> loops can be written using <tt>DO</tt>: |
The equivalent of other languages' <tt>FOR</tt> or <tt>DO</tt> loops can be written using <tt>DO</tt>: |
||
< |
<syntaxhighlight lang="xlisp">(DO ((I 1 (+ I 1))) ((> I 5)) |
||
(DO ((J 0 (+ J 1))) ((= J I)) |
(DO ((J 0 (+ J 1))) ((= J I)) |
||
(DISPLAY "*")) |
(DISPLAY "*")) |
||
(NEWLINE))</ |
(NEWLINE))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>* |
<pre>* |
||
Line 3,485: | Line 4,157: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code ChOut=8, CrLf=9; |
||
int I, J; |
int I, J; |
||
for I:= 1 to 5 do |
for I:= 1 to 5 do |
||
Line 3,491: | Line 4,163: | ||
ChOut(0, ^*); |
ChOut(0, ^*); |
||
CrLf(0); |
CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |
||
For the Amstrad CPC (should work with e.g. the built-in assembler in JavaCPC; use <tt>call &4000</tt> to start from BASIC): |
For the Amstrad CPC (should work with e.g. the built-in assembler in JavaCPC; use <tt>call &4000</tt> to start from BASIC): |
||
< |
<syntaxhighlight lang="z80">org &4000 ; put code at memory address 0x4000 |
||
wr_char equ &bb5a ; write ASCII character in register A to screen |
wr_char equ &bb5a ; write ASCII character in register A to screen |
||
; (jumps into CPC ROM) |
; (jumps into CPC ROM) |
||
Line 3,535: | Line 4,207: | ||
pop de |
pop de |
||
pop bc |
pop bc |
||
ret ; return to BASIC interpreter</ |
ret ; return to BASIC interpreter</syntaxhighlight> |
||
=={{header|Zig}}== |
|||
<syntaxhighlight lang="zig"> |
|||
const std = @import("std"); |
|||
pub fn main() !void { |
|||
const stdout_wr = std.io.getStdOut().writer(); |
|||
for (1..6) |n| { |
|||
for (0..n) |_| { |
|||
try stdout_wr.writeAll("*"); |
|||
} |
|||
try stdout_wr.writeAll("\n"); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
* |
|||
** |
|||
*** |
|||
**** |
|||
***** |
|||
</pre> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">foreach i in ([1..5]){ |
||
foreach j in (i){print("*")} |
foreach j in (i){print("*")} |
||
println(); |
println(); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Latest revision as of 12:47, 10 July 2024
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.
- 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:
* ** *** **** *****
- Related tasks
- Loop over multiple arrays simultaneously
- Loops/Break
- Loops/Continue
- Loops/Do-while
- Loops/Downward for
- Loops/For
- Loops/For with a specified step
- Loops/Foreach
- Loops/Increment loop index within loop body
- Loops/Infinite
- Loops/N plus one half
- Loops/Nested
- Loops/While
- Loops/with multiple ranges
- Loops/Wrong ranges
- Reference
- For loop Wikipedia.
11l
L(i) 1..5
L 1..i
print(‘*’, end' ‘’)
print()
Pythonic solution:
L(i) 1..5
print(‘*’ * i)
360 Assembly
- Basic - Algol style
The opcode BXH uses 3 registers, one for index, one for step and one for limit.
* Loops/For - BXH Algol 27/07/2015
LOOPFOR CSECT
USING LOOPFORC,R12
LR R12,R15 set base register
BEGIN LA R2,0 from 1 (from-step=0)
LA R4,1 step 1
LA R5,5 to 5
LOOPI BXH R2,R4,ELOOPI for i=1 to 5 (R2=i)
LA R8,BUFFER-1 ipx=-1
LA R3,0 from 1 (from-step=0)
LA R6,1 step 1
LR R7,R2 to i
LOOPJ BXH R3,R6,ELOOPJ for j:=1 to i (R3=j)
LA R8,1(R8) ipx=ipx+1
MVI 0(R8),C'*' buffer(ipx)='*'
B LOOPJ next j
ELOOPJ XPRNT BUFFER,L'BUFFER print buffer
B LOOPI next i
ELOOPI BR R14 return to caller
BUFFER DC CL80' ' buffer
YREGS
END LOOPFOR
- Output:
* ** *** **** *****
- Structured Macros
Structured and without BXH, only one register used by loop.
* Loops/For - struct 29/06/2016
LOOPFOR CSECT
USING LOOPFORC,R12
LR R12,R15 set base register
LA R2,1 from 1
DO WHILE=(CH,R2,LE,=H'5') for i=1 to 5 (R2=i)
LA R8,BUFFER-1 ipx=-1
LA R3,1 from 1
DO WHILE=(CR,R3,LE,R2) for j:=1 to i (R3=j)
LA R8,1(R8) ipx=ipx+1
MVI 0(R8),C'*' buffer(ipx)='*'
LA R3,1(R3) j=j+1 (step)
ENDDO , next j
XPRNT BUFFER,L'BUFFER print buffer
LA R2,1(R2) i=i+1 (step)
ENDDO , next i
BR R14 return to caller
BUFFER DC CL80' ' buffer
YREGS
END LOOPFOR
- Output:
Same as above
68000 Assembly
Although it's more natural for the language to loop downward rather than forward, both are possible.
main:
MOVEQ #1,D1 ;counter for how many times to print *, this is also the loop counter
.outerloop:
MOVE.W D1,D2
SUBQ.W #1,D2
.innerloop:
MOVE.B #'*',D0
JSR PrintChar ;hardware-dependent printing routine
DBRA D2,.innerloop ;DBRA loops until wraparound to $FFFF, which is why we subtracted 1 from D2 earlier.
JSR NewLine ;hardware-dependent newline routine
ADDQ.W #1,D1
CMP.W #6,D1 ;are we done yet?
BCS .outerloop ;if not, go back to the top
RTS
8086 Assembly
The following works with MS-DOS. Called as a subroutine (i.e. "call StarSub")
StarSub:
mov ah,02h ;needed to prime the interrupt command for printing to screen
mov ch,1 ;outer loop counter
outer_loop:
mov cl,ch ;refresh the inner loop counter, by copying the value of the outer loop counter to it.
;each time the inner loop finishes, it will last one iteration longer the next time.
inner_loop:
mov dl,02Ah ;ascii for *
int 21h ;tells DOS to print the contents of dl to the screen
dec cl
jnz inner_loop
mov dl,13 ;Carriage Return
int 21h
mov dl,10 ;New Line
int 21h
inc ch ;make the outer loop counter bigger for next time.
cmp ch,5
jnz outer_loop
ret
8th
This illustrates two kinds of 'for' loop. The first kind is "loop", which iterates from the low to the high value, and passes the current loop index as a parameter to the inner word. The second is 'times', which takes a count and repeats the word that many times.
( ( '* putc ) swap times cr ) 1 5 loop
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loop64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessX: .asciz "X"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
mov x2,0 // counter loop 1
1: // loop start 1
mov x1,0 // counter loop 2
2: // loop start 2
ldr x0,qAdrszMessX
bl affichageMess
add x1,x1,1 // x1 + 1
cmp x1,x2 // compare x1 x2
ble 2b // loop label 2 before
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x2,x2,1 // x2 + 1
cmp x2,#5 // for five loop
blt 1b // loop label 1 before
100: // standard end of the program */
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessX: .quad szMessX
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
Action!
Proc Main()
byte I,J
For I=1 to 5
Do
For J=1 to I
Do
Print("*")
Od
PrintE("")
Od
Return
ActionScript
var str:String = "";
for (var i:int = 1; i <= 5; i++) {
for (var j:int = 1; j <= i; j++)
str += "*";
trace(str);
str = "";
}
Ada
for I in 1..5 loop
for J in 1..I loop
Put("*");
end loop;
New_Line;
end loop;
Agena
Tested with Agena 2.9.5 Win32
for i to 5 do
for j to i do
write( "*" )
od;
print()
od
ALGOL 60
INTEGER I,J;
FOR I:=1 STEP 1 UNTIL 5 DO
BEGIN
FOR J:=1 STEP 1 UNTIL I DO
OUTTEXT("*");
OUTLINE
END
ALGOL 68
FOR i TO 5 DO
TO i DO
print("*")
OD;
print(new line)
OD
- Output:
* ** *** **** *****
ALGOL W
In Algol W, write starts a new line, writeon continues it.
begin
for i := 1 until 5 do
begin
write( "*" );
for j := 2 until i do
begin
writeon( "*" )
end j
end i
end.
ALGOL-M
BEGIN
INTEGER I, J;
FOR I := 1 STEP 1 UNTIL 5 DO
BEGIN
WRITE( "" );
FOR J := 1 STEP 1 UNTIL I DO
WRITEON( "*" );
END;
END
- Output:
* ** *** **** *****
Alore
for i in 0 to 6
for j in 0 to i
Write('*')
end
WriteLn()
end
AmigaE
PROC main()
DEF i, j
FOR i := 1 TO 5
FOR j := 1 TO i DO WriteF('*')
WriteF('\n')
ENDFOR
ENDPROC
Apex
for (Integer i = 0; i < 5; i++) {
String line = '';
for (Integer j = 0; j < i; j++) {
line += '*';
}
System.debug(line);
}
List<String> lines = new List<String> {
'*',
'**',
'***',
'****',
'*****'
};
for (String line : lines) {
System.debug(line);
}
APL
For most purposes, the APL analogue of a for loop is the each operator ¨. The most natural way to accomplish this task doesn't use a nested each, but the repeat operator / inside a single each:
stars ← { ⍵ 1 ⍴ {⍵/'*'}¨⍳⍵ }
To stick to the letter of the task description, we can nest an each inside another one, but it's a little silly. Plus not all dialects support niladic dfns, so the innermost "return one star" function has to take a dummy argument:
stars ← { ⍵ 1 ⍴ { {1⌷'*',⍵} ¨ ⍳⍵ } ¨ ⍳⍵ }
Additionally, Dyalog and some other dialects support the more traditional structured programming controls inside a named function definition (tradfn):
∇result ← stars count; i; j; vec
vec ← ⍬
:for i :in ⍳ count
vec ,← ⊂''
:for j :in ⍳ i
vec[i],←'*'
:endfor
:endfor
result ← count 1 ⍴ vec
∇
- Output:
The result of all three implementations of stars is a column vector, which is displayed like this:
stars 5 * ** *** **** *****
AppleScript
set x to linefeed
repeat with i from 1 to 5
repeat with j from 1 to i
set x to x & "*"
end repeat
set x to x & linefeed
end repeat
return x
- Output:
* ** *** **** *****
ARM Assembly
/* ARM assembly Raspberry PI */
/* program loop1.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessX: .asciz "X"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
mov r2,#0 @ counter loop 1
1: @ loop start 1
mov r1,#0 @ counter loop 2
2: @ loop start 2
ldr r0,iAdrszMessX
bl affichageMess
add r1,#1 @ r1 + 1
cmp r1,r2 @ compare r1 r2
ble 2b @ loop label 2 before
ldr r0,iAdrszCarriageReturn
bl affichageMess
add r2,#1 @ r2 + 1
cmp r2,#5 @ for five loop
blt 1b @ loop label 1 before
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszMessX: .int szMessX
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
Arturo
loop 0..5 'x [
loop 0..x 'y [
prints "*"
]
print ""
]
- Output:
* ** *** **** ***** ******
Asymptote
Asymptote's control structures are similar to those in C, C++, or Java
for(int i = 0; i < 6; ++i) {
for(int j = 0; j < i; ++j) {
write("*", suffix=none);
}
write("");
}
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
Avail
For each row from 1 to 5 do
[
For each length from 1 to row do [Print: "*";];
Print: "\n";
];
Since the inner loop index is unneeded, it may be more natural to use the From_to_do_
loop format:
For each row from 1 to 5 do
[
From 1 to row do [Print: "*";];
Print: "\n";
];
AWK
BEGIN {
for(i=1; i < 6; i++) {
for(j=1; j <= i; j++ ) {
printf "*"
}
print
}
}
Axe
In this example, the Axe code is nearly identical to the TI-83 BASIC version. However, note the swapped order of the I and J in the Output() statement. Also, unlike TI-83 BASIC, Axe does not support an increment value other than 1.
ClrHome
For(I,1,5)
For(J,1,I)
Output(J,I,"*")
End
End
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.
Bait
const ROWS := 5
fun main() {
for i := 1; i <= ROWS; i += 1 {
for j := 1; j <= i; j += 1 {
print('*')
}
println('')
}
}
bash
for i in {1..5}
do
for ((j=1; j<=i; j++));
do
echo -n "*"
done
echo
done
BASIC
for i = 1 to 5
for j = 1 to i
print "*";
next j
print
next i
Applesoft BASIC
FOR I = 1 TO 5 : FOR J = 1 TO I : PRINT "*"; : NEXT J : PRINT : NEXT
BASIC256
for i = 1 to 5
for j = 1 to i
print "*";
next j
print
next i
end
BaCon
FOR i = 1 TO 5
FOR j = 1 TO i
PRINT "*"
NEXT
PRINT
NEXT
BBC BASIC
FOR I% = 1 TO 5
FOR J% = 1 TO I%
PRINT"*";
NEXT
PRINT
NEXT
Chipmunk Basic
10 for i = 1 to 5
20 for j = 1 to i
30 print "*";
40 next j
50 print
60 next i
Commodore BASIC
10 FOR I = 1 TO 5
20 : FOR J = 1 TO I
30 : PRINT "*";
40 : NEXT J
50 : PRINT
60 NEXT I
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
GW-BASIC
10 FOR I = 1 TO 5
20 FOR J = 1 TO I
30 PRINT "*";
40 NEXT J
50 PRINT
60 NEXT I
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...
FUZE BASIC
FOR n = 1 to 5 CYCLE
FOR k = 1 to n CYCLE
print "*";
REPEAT
PRINT
REPEAT
END
IS-BASIC
100 FOR I=1 TO 5
110 FOR J=1 TO I
120 PRINT "*";
130 NEXT
140 PRINT
150 NEXT
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.
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
MSX Basic
The GW-BASIC solution works without any changes.
Microsoft Small Basic
For i = 1 To 5
For j = 1 To i
TextWindow.Write("*")
EndFor
TextWindow.WriteLine("")
EndFor
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
QBasic
The GW-BASIC solution works without any changes. Also The BASIC256 solution works without any changes.
Quite BASIC
The GW-BASIC solution works without any changes.
Run BASIC
FOR i = 1 TO 5
FOR j = 1 TO i
PRINT "*";
NEXT j
PRINT
NEXT i
SmallBASIC
for a = 1 to 5
for b = 1 to a
print "*";
next
print
next
smart BASIC
While some versions of BASIC allow for NEXT without a variable, smart BASIC requires the variable designation.
for n = 1 to 5
for m = 1 to n
print "*";
next m
print
next n
True BASIC
FOR i = 1 TO 5
FOR j = 1 TO i
PRINT "*";
NEXT j
PRINT
NEXT i
END
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
Visual Basic .NET
For x As Integer = 0 To 4
For y As Integer = 0 To x
Console.Write("*")
Next
Console.WriteLine()
Next
Yabasic
for i = 1 to 5
for j = 1 to i
print "*";
next j
print
next i
end
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
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
bc
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++) "*"
"
"
}
quit
BCPL
get "libhdr"
let start() be
for i = 1 to 5
$( for j = 1 to i do wrch('**')
wrch('*N')
$)
Befunge
1>:5`#@_:>"*",v
| :-1<
^+1,+5+5<
Binary Lambda Calculus
The following 22-byte BLC program is generated from https://github.com/tromp/AIT/blob/master/rosetta/forloops.lam :
18 18 11 50 73 9c e7 40 b3 df cb df 38 1c bd a3 88 05 bb 00 2a 0a
blz
for i = 1; i <= 5; i++
line = ""
for (j = 1; j <= i; j++)
line = line + "*"
end
print(line)
end
Bracmat
0:?i
& whl
' ( !i+1:~>5:?i
& 0:?k
& whl'(!k+1:~>!i:?k&put$"*")
& put$\n
)
&
);
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
Brat
1.to 5, { i |
1.to i, { j |
print "*"
}
print "\n"
}
C
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++)
putchar('*');
puts("");
}
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();
}
}
}
C++
for(int i = 0; i < 5; ++i) {
for(int j = 0; j < i; ++j)
std::cout.put('*');
std::cout.put('\n');
}
C3
for (int i = 0; i < 5; i++)
{
for (int j = 1; j <= i; j++) io::print("*");
io::printn("*");
}
Ceylon
shared void run() {
for(i in 1..5) {
for(j in 1..i) {
process.write("*");
}
print("");
}
}
Chapel
for i in 1..5 {
for 1..i do write('*');
writeln();
}
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.
Clojure
(doseq [i (range 5), j (range (inc i))]
(print "*")
(if (= i j) (println)))
CLU
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(1, 5) do
for j: int in int$from_to(1, i) do
stream$putc(po, '*')
end
stream$putl(po, "")
end
end start_up
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
.
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
(loop for i from 1 upto 5 do
(loop for j from 1 upto i do
(write-char #\*))
(terpri))
or
(dotimes (i 5)
(dotimes (j (+ i 1))
(write-char #\*))
(terpri))
or
(do ((i 1 (+ i 1)))
((> i 5))
(do ((j 1 (+ j 1)))
((> j i))
(write-char #\*))
(terpri))
or
(use-package :iterate)
(iter
(for i from 1 to 5)
(iter
(for j from 1 to i)
(princ #\*))
(terpri))
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.
Cowgol
include "cowgol.coh";
var i: uint8 := 1;
while i <= 5 loop
var j: uint8 := 1;
while j <= i loop
print_char('*');
j := j + 1;
end loop;
print_nl();
i := i + 1;
end loop;
Crystal
1.upto(5) do |i|
1.upto(i) do |j|
print "*"
end
puts
end
Or another way, more succinctly put:
puts (1..5).map { |i| "*" * i }.join("\n")
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:
* ** *** **** ***** * ** *** **** *****
Dao
for( i = 1 : 5 ){
for( j = 1 : i ) io.write( '*' )
io.writeln()
}
Dart
main() {
for (var i = 0; i < 5; i++)
for (var j = 0; j < i + 1; j++)
print("*");
print("\n");
}
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.
[
[*]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
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.
Diego
set_ns(rosettacode);
add_var({str},s)_value();
add_var({str},output);
add_for({int},i)_from(1)_uptoand(5)_inc()
with_var(s)_v();
add_for({int},j)_from(0)_upto([i])_inc()
with_var(s)_calc([s]&="*");
;
with_var(output)_calc(&=[s]&\n);
;
me_msg([output]);
reset_ns[];
DMS
number i, j
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
Result( "*" )
}
Result( "\n" )
}
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()
Draco
proc nonrec main() void:
byte i,j;
for i from 1 upto 5 do
for j from 1 upto i do
write("*")
od;
writeln()
od
corp
- Output:
* ** *** **** *****
Dragon
for (i = 0, i < 5, i++) {
for (j = 0, j <= i, j++) {
show "*"
}
showln ""
}
DWScript
var i, j : Integer;
for i := 1 to 5 do begin
for j := 1 to i do
Print('*');
PrintLn('');
end;
Dyalect
for i in 1..5 {
for _ in 1..i {
print("*", terminator: "")
}
print()
}
Output:
* ** *** **** *****
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.)
EasyLang
for i = 1 to 5
for j = 1 to i
write "*"
.
print ""
.
Ed
Uses unary i-encoded numbers for state and turns them into asterisks before printing.
H
a
iiiii
.
s/\B/\
/g
a
.
y
d
g/i/x\
s/.*/&*/\
-1d\
y
,p
Q
EDSAC order code
As with many other machine-level languages, there is no inbuilt looping construct; but the equivalent of a FOR or DO loop can easily be synthesized using conditional branching orders and a control variable.
The EDSAC character set does not include a * character, so + has been used instead.
Characters are encoded in five-bit form, with each code point producing a different character depending on whether the machine is in 'letter' or 'figure' mode: this is why it is necessary to output a 'figure shift' control character at the beginning of the job.
[ Loops
=====
A program for the EDSAC
Demonstrates nested loops
and printer output
Works with Initial Orders 2 ]
T56K [ set load point ]
GK [ set theta ]
O21@ [ figure shift ]
[ 1 ] T24@ [ a = 0 ]
A19@ [ a = i ]
[ 3 ] T20@ [ j = a; a = 0 ]
O22@ [ write character ]
A20@ [ a = j ]
S17@ [ a -= 1 ]
U20@ [ j = a ]
E3@ [ if a>=0 go to 3 ]
O23@ [ write line feed ]
T24@ [ a = 0 ]
A19@ [ a = i ]
A17@ [ a += 1 ]
U19@ [ i = a ]
S18@ [ a -= 5 ]
G1@ [ if a<0 go to 1 ]
ZF [ halt ]
[ 17 ] P0D [ const: 1 ]
[ 18 ] P2D [ const: 5 ]
[ 19 ] P0F [ var: i ]
[ 20 ] P0F [ var: j ]
[ 21 ] #F [ figure shift ]
[ 22 ] ZF [ '+' character ]
[ 23 ] &F [ line feed ]
[ 24 ] P0F [ used to clear a ]
EZPF [ begin execution ]
- Output:
+ ++ +++ ++++ +++++
EGL
str string;
for ( i int to 5 )
str = "";
for ( j int to i )
str += "*";
end
SysLib.writeStdout(str);
end
Ela
open monad io
loop m n | n < m = do
loop' n 0
putStrLn ""
loop m (n + 1)
| else = do return ()
where loop' m n | n <= m = do
putStr "*"
loop' m (n + 1)
| else = do return ()
_ = loop 10 1 ::: IO
Output:
**
***
****
*****
******
*******
********
*********
**********
Elena
ELENA 6.x :
import extensions;
public program()
{
for(int i := 0; i < 5; i += 1)
{
for(int j := 0; j <= i; j += 1)
{ console.write("*") };
console.writeLine()
}
}
- Output:
* ** *** **** *****
Elixir
defmodule Loops do
def loops_for(n) do
Enum.each(1..n, fn i ->
Enum.each(1..i, fn _ -> IO.write "*" end)
IO.puts ""
end)
end
end
Loops.loops_for(5)
one line (Comprehensions)
for i <- 1..5, do: IO.puts (for j <- 1..i, do: "*")
Emacs Lisp
;; Lisp implementation of c-for is like:
;; (let ((i nil))
;; (while (progn (setq i (if (not i) 0 (1+ i) )) ;; if value of i is nil, initialize its value to 0, if else, add 1
;; (< i 10)) ;; end loop when i > 10
;; (... body ...) ) ) ;; loop body
(let ((i nil) (str ""))
(while (progn (setq i (if (not i) 0 (1+ i) ))
(< i 5))
(setq str (concat str "*"))
(message str) ) )
output logged in buffer *Messages*:
* ** *** **** *****
EMal
for int i = 0; i < 5; ++i
for int j = 0; j <= i; ++j do write("*") end
writeLine()
end
- Output:
* ** *** **** *****
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).
ERRE
FOR I=1 TO 5 DO
FOR J=1 TO I DO
PRINT("*";)
END FOR
PRINT
END FOR
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 sequence
s; 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.
F#
#light
[<EntryPoint>]
let main args =
for i = 1 to 5 do
for j = 1 to i do
printf "*"
printfn ""
0
Factor
5 [1,b] [ [ "*" write ] times nl ] each
FALSE
1[$6-][$[$]["*"1-]#%"
"1+]#%
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 ("")
}
}
}
Fennel
(for [i 1 4]
(for [j 1 i]
(io.write "*"))
(print))
Fermat
for i = 1 to 5 do for j = 1 to i do !'*'; od; !; od
FOCAL
When the program exits the outer loop, the control variable I is set to 4 + 1 = 5; we can therefore permit execution to fall through into the inner loop for one more iteration.
01.10 FOR I=1,4; DO 2.0
02.10 FOR J=1,I; TYPE "*"
02.20 TYPE !
- Output:
* ** *** **** *****
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?)
Fortran
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
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.
integer :: i
integer, dimension(10) :: v
forall (i=1:size(v)) v(i) = i
But if one accepts that a do-loop can be expressed without the actual word "do" (or "for"), then
DO 1 I = 1,5
1 WRITE (6,*) ("*", J = 1,I)
END
That is a complete programme, though a more polite source file would have INTEGER I,J. It uses the old-style DO label etc. style of DO-loop to save on having to specify an END DO. The WRITE statement's output list is generated by an "implied" DO-loop having much of the form of DO J = 1,I and is indeed a proper loop. The output item is a text literal, which in earlier Fortran was unknown, however the result can still be achieved:
DO 1 I = 1,5
1 WRITE (6,2) (666, J = 1,I)
2 FORMAT(5I1)
END
This works because if a value cannot be fitted into its output field, the field is filled with asterisks. Which, is what is wanted! Just allow one digit for output (I1), and present a large integer.
FreeBASIC
' FB 1.05.0 Win64
For i As Integer = 1 To 5
For j As Integer = 1 To i
Print "*";
Next
Print
Next
Sleep
- Output:
* ** *** **** *****
Frink
for n = 1 to 5
{
for a = 1 to n
print["*"]
println[]
}
Futhark
Futhark does not have I/O, so this program simply counts in the inner loop.
fun main(n: int): [n]int =
loop (a = replicate n 0) = for i < n do
(loop (s = 0) = for j < i+1 do
s + j
let a[i] = s
in a)
in a
FutureBasic
window 1
long i, j
for i = 1 to 5
for j = 1 to i
print @"*";
next
print
next
HandleEvents
Gambas
Click this link to run this code
Public Sub Main()
Dim i, j As Integer
For i = 1 To 5
For j = 1 To i
Print "*";
Next
Print
Next
End
* ** *** **** *****
GAP
for i in [1 .. 5] do
for j in [1 .. i] do
Print("*");
od;
Print("\n");
od;
# *
# **
# ***
# ****
# *****
GML
pattern = ""
for(i = 1; i <= 5; i += 1)
{
for(j = 1; j <= i; j += 1)
{
pattern += "*"
}
pattern += "#"
}
show_message(pattern)
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:
* ** *** **** *****
Groovy
Solution:
for(i in (1..6)) {
for(j in (1..i)) {
print '*'
}
println ()
}
GW-BASIC
100 FOR I=1 TO 5
110 FOR J=1 TO I
120 PRINT "*";
130 NEXT J
140 PRINT
150 NEXT I
160 END
- Output:
* ** *** **** *****
Hack
for($i = 0; $i < 5; $i++) {
for($j = 0; $j <= $i; $j++) {
echo '*';
}
echo '\n';
}
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 '*'
Or, with a list comprehension:
putStrLn $ unlines [replicate n '*' | n <- [1..5]]
Taking from an infinite stream of increasing length lines:
putStrLn . unlines . take 5 $ iterate ('*':) "*"
Haxe
for (i in 1...6) {
for(j in 0...i) {
Sys.print('*');
}
Sys.println('');
}
hexiscript
for let i 1; i <= 5; i++
for let j 1; j <= i; j++
print "*"
endfor
println ""
endfor
HicEst
DO i = 1, 5
DO j = 1, i
WRITE(APPend) "*"
ENDDO
WRITE() ' '
ENDDO
HolyC
U8 i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++)
Print("*");
Print("\n");
}
Icon and Unicon
Icon
Unicon
The Icon solution works in Unicon.
Inform 7
repeat with length running from 1 to 5:
repeat with N running from 1 to length:
say "*";
say line break;
J
J is array-oriented, so there is very little need for loops. For example:
]\ '*****'
*
**
***
****
*****
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).
{{
for_i. i. y do.
z=. ''
for. i. i do.
z=. z,'*'
end.
echo z
end.
EMPTY
}}0
But you would almost never see J code like this.
Java
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
JavaScript
var i, j;
for (i = 1; i <= 5; i += 1) {
s = '';
for (j = 0; j < i; j += 1)
s += '*';
document.write(s + '<br>');
}
Alternatively, using JavaScript's Array.forEach(), and given an array of indices,
or a simple range function which generates a range:
function range(i) {
return i ? range(i - 1).concat(i) : [];
}
range(5) --> [1, 2, 3, 4, 5]
We could write something like:
var s = '';
range(5).forEach(
function (line) {
range(line).forEach(
function () { s += '*'; }
);
s += '\n';
}
);
console.log(s);
but it might be more natural in JavaScript, if we are going to use built-in Array functions, to simplify a little with Array.reduce(), writing:
console.log(
range(5).reduce(
function (a, n) {
return a + Array(n + 1).join('*') + '\n';
}, ''
)
);
in which the inner n refers to the Array value visited at the next level out, and the triangle is returned as a single expression, rather than as a series of variable mutations.
Finally, in contexts where an expression composes better than a statement, the effect of a loop can often be expressed as a map.
console.log(
range(5).map(function(a) {
return Array(a + 1).join('*');
}).join('\n')
);
Jinja
Variable usage inside a loop, before version 2.10 :
print(Template("""{% set sum = 0 %}
{% for i in range(6) %}
{{ sum }}{% set sum = sum + i %}
{%- endfor %}""").render())
Since 2.10 :
print(Template("""{% set sum = namespace(value=0) %}
{% for i in range(6) %}
{{ sum.value }}{% set sum.value = sum.value + i %}
{%- endfor %}""").render())
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 * ** *** **** *****
Jsish
Code from Javascript entry.
var i, j, s;
for (i = 1; i <= 5; i += 1) {
s = '';
for (j = 0; j < i; j += 1) s += '*';
puts(s);
}
- Output:
prompt$ jsish forloop.jsi * ** *** **** *****
Julia
for i in 1:5
for j in 1:i
print("*")
end
println()
end
- Output:
* ** *** **** *****
Klong
:" x{p}:*y means repeat {p} x times starting at y "
5{x{.d(0c*);x}:*0;.p("");x+1}:*1
:" But you would not do it like this! "
:" You would reshape 0c* to the desired length "
:" in a function and then iterate that function "
:" over a vector of numbers: "
{.p(x:^0c*)}'1+!5
Kotlin
fun main(args: Array<String>) {
(1..5).forEach {
(1..it).forEach { print('*') }
println()
}
}
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.
Lambdatalk
{def loops_for
{lambda {:i :n}
{if {>= :i :n}
then (end of loop)
else {br}{S.map {lambda {} *} {S.serie 0 :i}}
{loops_for {+ :i 1} :n}}}}
-> loops_for
{loops_for 0 5}
->
*
* *
* * *
* * * *
* * * * * (end of loop)
a simpler way, using {S.map function {S.serie start end [step]}
{S.map {lambda {:i} {br}
{S.map {lambda {:i} *}
{S.serie 1 :i}}}
{S.serie 1 5}}
->
*
* *
* * *
* * * *
* * * * *
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
langur
for i = 0; i < 5; i += 1 {
for j = 0; j <= i; j += 1 {
write "*"
}
writeln()
}
A for of loop iterates over keys (when used with an array, string, or hash) and a for in loop iterates over values.
for i of 5 {
for of i {
write "*"
}
writeln()
}
Or, with one for loop...
for i of 5 {
writeln "*" * i
}
Lasso
loop(5) => {^
loop(loop_count) => {^ '*' ^}
'\r'
^}
LC3 Assembly
.ORIG 0x3000
AND R1,R1,0
ADD R1,R1,1
AND R5,R5,0
ADD R5,R5,5
NOT R5,R5
LOOPI LD R0,STAR
AND R2,R2,0
ADD R3,R1,0
LOOPJ OUT
ADD R2,R2,1
NOT R4,R2
ADD R4,R3,R4
BRZP LOOPJ
LD R0,LF
OUT
ADD R1,R1,1
ADD R4,R1,R5
BRN LOOPI
HALT
STAR .FILL 0x2A
LF .FILL 0x0A
.END
Output:
* ** *** **** *****
LDPL
data:
i is number
j is number
procedure:
for i from 1 to 6 step 1 do
for j from 0 to i step 1 do
display "*"
repeat
display lf
repeat
- Output:
* ** *** **** *****
LIL
In LIL for takes a before loop code block for init, a conditional expression (true to enter loop step, false to exit loop), an after each loop step code block for value reassignment, followed by the code for the loop.
for {set i 1} {$i <= 5} {inc i} {
for {set j 1} {$j <= $i} {inc j} {
write "*"
}
print
}
- Output:
prompt$ lil loopsFor.lil * ** *** **** *****
The for statement in LIL, like Tcl, is pretty flexible and is not limited to simple incremented variable style loops.
Lingo
repeat with i = 1 to 5
str = ""
repeat with j = 1 to i
put "*" after str
end repeat
put str
end repeat
Lisaac
1.to 5 do { i : INTEGER;
1.to i do { dummy : INTEGER;
'*'.print;
};
'\n'.print;
};
LiveCode
put 0 into n
repeat for 5 times
add 1 to n
repeat for n times
put "*"
end repeat
put return
end repeat
Logo
for [i 1 5] [repeat :i [type "*] (print)]
repeat 5 [repeat repcount [type "*] (print)]
Lua
for i=1,5 do
for j=1,i do
io.write("*")
end
io.write("\n")
end
single loop
for i = 1, 5 do
print(string.rep("*", i))
end
or
for i = 1, 5 do
print(("*"):rep(i))
end
M2000 Interpreter
By default there For loops always perform on execution of block. If end value is smaller than fist value, then step adjust to that direction. When first value is equal to second value then if we declare step negative end value after execution of block became start value minus absolute step, or if step is positive, became start value plus step. We can use a switch for interpreter to change IF's STEP to act as BASIC's, and sign of step always used, and there is situations where block can't executed.
For i=1 to 5
For j=1 to i
Print "*";
Next j
Print
Next i
Print "End1"
For i=1 to 5 {
For j=1 to i {
Print "*";
}
Print
}
Print "End2"
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',
`*')
')
make
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
Maple
> for i to 5 do to i do printf( "*" ) end; printf( "\n" ) end;
*
**
***
****
*****
Mathematica /Wolfram Language
n=5;
For[i=1,i<=5,i++,
string="";
For[j=1,j<=i,j++,string=string<>"*"];
Print[string]
]
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
Maxima
for i thru 5 do (
s: "",
thru i do s: sconcat(s, "*"),
print(s)
);
MAXScript
for i in 1 to 5 do
(
line = ""
for j in 1 to i do
(
line += "*"
)
format "%\n" line
)
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).
MiniScript
Literal interpretation of the task is somewhat complicated by the fact that the standard implementation of print
in MiniScript adds a line break:
for i in range(1,5)
s = ""
for j in range(1, i)
s = s + "*"
end for
print s
end for
- Output:
* ** *** **** *****
However, it is worth noting that MiniScript's string replication operator (*) makes a more natural solution possible:
for i in range(1,5)
print "*" * i
end for
(Output same as above.)
MIPS Assembly
Thanks to ChibiAliens for the header and footer as well as print routines.
.include "\SrcAll\Header.asm"
.include "\SrcAll\BasicMacros.asm"
.include "\SrcPSX\MemoryMap.asm"
.include "\SrcN64\MemoryMap.asm"
CursorX equ 0x100
CursorY equ 0x101
main:
li t3,5+1 ;outer loop counter
li t2,1 ;inner loop counter
move a2,t2 ;working copy of inner loop counter
loop:
li a1,'*'
jal PrintChar
nop ;needed on PlayStation after branches to prevent out-of-order execution.
subiu a2,1
bnez a2,loop
nop
;overhead
jal NewLine ;this doesn't use t2 so we don't care about out-of-order execution.
addiu t2,1 ;increment outer loop counter
move a2,t2 ;next time, we'll print one more * than we did last time.
bne t2,t3,loop ;are we done yet? If not, loop.
nop
HALT:
j HALT ;halt the CPU - we're done
nop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MyFont:
.ifdef buildn64
.incbin "\ResN64\ChibiAkumas.fnt"
.endif
.ifdef buildPSX
.incbin "\ResPSX\ChibiAkumas.fnt"
.endif
.include "\SrcALL\graphics.asm"
.include "..\\SrcAll\monitor.asm"
.include "\SrcN64\Footer.asm"
- Output:
* ** *** **** *****
Screenshot of Nintendo 64 emulator
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.
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.
MOO
for i in [1..5]
s = "";
for j in [1..i]
s += "*";
endfor
player:tell(s);
endfor
Morfa
import morfa.base;
for (i in 0..5)
{
for (j in 0..i+1)
{
print("*");
}
println("");
}
MUMPS
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 * ** *** **** *****
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 !
Nanoquery
for ($i = 1) ($i <= 5) ($i = $i+1)
for ($j = 0) ($j < $i) ($j = $j+1)
print "*"
end for
println
end for
Nemerle
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
Write("*");
}
WriteLine();
}
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_
NewLISP
(for (i 1 5)
(for(j 1 i)
(print "*"))
(print "\n"))
Nim
for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
NS-HUBASIC
10 FOR I=1 TO 5
20 FOR J=1 TO I
30 PRINT "*";
40 NEXT
50 PRINT
60 NEXT
Nu
for i in 1..5 {
for j in 1..$i {
print -n "*"
}
print ""
}
Oberon-2
Works with oo2c Version 2
MODULE LoopFor;
IMPORT
Out;
VAR
i, j: INTEGER;
BEGIN
FOR i := 1 TO 5 DO
FOR j := 1 TO i DO
Out.Char('*');
END;
Out.Ln
END
END LoopFor.
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();
};
}
}
}
OCaml
for i = 1 to 5 do
for j = 1 to i do
print_string "*"
done;
print_newline ()
done
Octave
for i = 0:1:4
for j = 0:1:i
printf("*");
endfor
printf("\n");
endfor
Odin
package main
import "core:fmt"
main :: proc() {
for i := 1 ; i <= 5 ; i += 1 {
for j := 1; j <= i; j += 1 {
fmt.printf("*")
}
fmt.println()
}
}
Oforth
: loopFor(n)
| i j |
n loop: i [
i loop: j [ "*" print ]
printcr ;
Onyx
1 1 5 {dup {`*'} repeat bdup bpop ncat `\n' cat print} for flush
Using repeat inside the for loop instead of nesting another for loop is shorter and more efficient.
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.)
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.
Panoramic
dim x,y
for x=1 to 5
for y=1 to x
print "*";
next y
print
next x
PARI/GP
for(a=1,5,for(b=1,a,print1("*"));print())
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.
PascalABC.NET
##
for var i:=1 to 5 do
begin
for var j:=1 to i do
Write('*');
Writeln
end;
Perl
for(my $x = 1; $x <= 5; $x++) {
for(my $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;
or equivalently
map {print '*' x $_ . "\n"} 1..5;
Phix
for i=1 to 5 do for j=1 to i do puts(1,"*") end for puts(1,"\n") end for
Phixmonti
/# Rosetta Code problem: https://rosettacode.org/wiki/Loops/For
by Galileo, 11/2022 #/
include ..\Utilitys.pmt
5 for
for
"*" print
endfor
nl
endfor
5 for '*' swap repeat ? endfor
- Output:
* ** *** **** ***** * ** *** **** ***** === Press any key to exit ===
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";
}
or
foreach (range(1, 5) as $i)
echo str_repeat('*', $i) , PHP_EOL;
Picat
go =>
N = 5,
foreach(I in 1..N)
foreach(_J in 1..I)
print("*")
end,
nl
end.
PicoLisp
(for N 5
(do N (prin "*"))
(prinl) )
Pike
int main(){
for(int i = 1; i <= 5; i++){
for(int j=1; j <= i; j++){
write("*");
}
write("\n");
}
}
PILOT
Core PILOT does not offer any way of printing without a newline, so in the inner loop we concatenate another star onto the string variable $stars
each time round and then print it in the outer loop.
C :i = 1
*OuterLoop
C :j = 0
C :$stars =
*InnerLoop
C :j = j + 1
C :$stars =*$stars
J ( j < i ) :*InnerLoop
T :$stars
C :i = i + 1
J ( i < 6 ) :*OuterLoop
END:
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 */
Plain English
Plain English doesn't allow the direct nesting of loops. Instead, you are encouraged to make one routine for each loop and let the routine headers describe what the loops are doing.
To run:
Start up.
Write a triangle of asterisks on the console given 5.
Wait for the escape key.
Shut down.
To write a row of asterisks on the console given a number:
If a counter is past the number, write "" on the console; exit.
Write "*" on the console without advancing.
Repeat.
To write a triangle of asterisks on the console given a size:
If a counter is past the size, exit.
Write a row of asterisks on the console given the counter.
Repeat.
Pop11
lvars i, j;
for i from 1 to 5 do
for j from 1 to i do
printf('*','%p');
endfor;
printf('\n')
endfor;
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 "*" * $_
.
Processing
size( 105,120 );
for ( int i=20; i<=100; i+=20 )
for ( int j=10; j<=i; j+=20 )
text( "*", j,i );
Prolog
Prolog has a built in iterator, between(Lo,Hi,I) which binds the value of I to successive values from Lo to Hi. This is the closest thing Prolog has to a 'for' loop.
example :-
between(1,5,I), nl, between(1,I,_J),
write('*'), fail.
example.
?- example. * ** *** **** ***** true.
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
or
print('\n'.join('*' * i for i in range(1, 6)))
QB64
CBTJD: 2020/03/14
FOR c = 1 TO 5
FOR n = 1 TO c
PRINT "*";
NEXT
PRINT
NEXT
Quackery
5 times [ i^ 1+ times [ say "*" ] cr ]
- Output:
* ** *** **** *****
R
for(i in 0:4) {
s <- ""
for(j in 0:i) {
s <- paste(s, "*", sep="")
}
print(s)
}
Racket
(for ([i (in-range 1 6)]) (for ([j i]) (display "*")) (newline))
Raku
(formerly Perl 6)
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;
Rapira
for N from 1 to 5 do
output: "*" * N
od
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 ""
]
Red
Red[]
repeat i 5 [
loop i [prin "*"]
prin newline
]
ReScript
let s = ref("")
for i in 1 to 5 {
for _ in 1 to i {
s := Js.String2.concat(s.contents, "*")
}
s := Js.String2.concat(s.contents, "\n")
}
Js.log(s.contents)
- Output:
bsc for.res > for.js node for.js * ** *** **** *****
Retro
6 [ 0; cr [ '* emit ] times ] iter
REXX
using concatenation
/*REXX program demonstrates an outer DO loop controlling the inner DO loop with a "FOR".*/
do j=1 for 5 /*this is the same as: do j=1 to 5 */
$= /*initialize the value to a null string*/
do k=1 for j /*only loop for a J number of times*/
$= $ || '*' /*using concatenation (||) for build.*/
end /*k*/
say $ /*display character string being built.*/
end /*j*/ /*stick a fork in it, we're all done. */
- output:
* ** *** **** *****
using abutment
/*REXX program demonstrates an outer DO loop controlling the inner DO loop with a "FOR".*/
do j=1 for 5 /*this is the same as: do j=1 to 5 */
$= /*initialize the value to a null string*/
do k=1 for j /*only loop for a J number of times*/
$= $'*' /*using abutment for the construction. */
end /*k*/
say $ /*display character string being built.*/
end /*j*/ /*stick a fork in it, we're all done. */
- output is identical to the 1st REXX version.
Ring
can be done in just one line:
for i = 1 to 5 for x = 1 to i see "*" next see nl next
or multiple line
for i = 1 to 5
for x = 1 to i
see "*"
next
see nl
next
RPL
RPL provides two types of counting loops: FOR
..NEXT
and START
..NEXT
, the latter looping without providing access to its counter.
≪ 1 5 FOR j "" 1 j START "*" + NEXT NEXT ≫ 'LOOPS' STO
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 }
Rust
The compiler warns when you create an unused variable; here we use _ to avoid this effect.
fn main() {
for i in 0..5 {
for _ in 0..=i {
print!("*");
}
println!();
}
}
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");
};
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;
/* Possible without the inner loop. Notice TRIM is replaced with STRIP,
otherwise there is a blank space on the left */
data _null_;
length a $5;
do n=1 to 5;
a=strip(a) !! "*";
put a;
end;
run;
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;
Scala
for (i <- 1 to 5) {
for (j <- 1 to i)
print("*")
println()
}
Scheme
(do ((i 1 (+ i 1)))
((> i 5))
(do ((j 1 (+ j 1)))
((> j i))
(display "*"))
(newline))
Scilab
for i=1:5
s=""
for j=1:i
s=s+"*"
end
printf("%s\n",s)
end
- Output:
* ** *** **** *****
Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: I is 1;
var integer: J is 1;
begin
for I range 1 to 5 do
for J range 1 to I do
write("*");
end for;
writeln;
end for;
end func;
- Output:
* ** *** **** *****
SETL
for i in {1..5} loop
for j in {1..i} loop
nprint( '*' );
end loop;
print; -- new line
end loop;
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"
}
for-in loop:
for i in (1..5) {
for j in (1..i) { print '*' }
print "\n"
}
Idiomatic:
5.times { |i|
i.times { print '*' }
print "\n"
}
Simula
begin
integer i,j;
for i:=1 step 1 until 5 do
begin
for j:=1 step 1 until i do
outtext("*");
outimage
end
end
Slate
1 to: 5 do: [| :n | inform: ($* repeatedTimes: n)].
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:
1 to: 5 do: [ :n |
Stdout next: n put: $*; cr
]
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):
"*****" arb $ output fail
end
SNUSP
/ \ < < < < /<<<<<.\ . ? > \->>>>>/ > ! > > ! > />-\ />+>+\ ? ? \+</ \ -<</ < ! < + - > / !\?/# \+++++>+++++++++++++>\ /++++++++++++++++++++++/ \++++++++++++++++++++\ $/
* ** *** **** *****
Sparkling
for (var row = 1; row <= 5; row++) {
for (var col = 1; col <= row; col++) {
printf("*");
}
print();
}
Spin
con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial.spin"
pub main | m, n
ser.start(31, 30, 0, 115200)
repeat n from 1 to 5
repeat m from 1 to n
ser.tx("*")
ser.str(string(13,10))
waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0)
- Output:
* ** *** **** *****
SPL
> i, 1..5
> j, 1..i
#.output("*",#.rs)
<
#.output()
<
Stata
forvalues n=1/5 {
local s ""
forvalues i=1/`n' {
local s `s'*
}
display "`s'"
}
Mata
for (i=1; i<=5; i++) {
for (j=1; j<=i; j++) printf("*")
printf("\n")
}
Suneido
for(i = 0; i < 5; ++i)
{
str = ''
for (j = 0; j <= i; ++j)
str $= '*'
Print(str)
}
Swift
for i in 1...5 {
for _ in 1...i {
print("*", terminator: "")
}
print()
}
- Output:
* ** *** **** *****
Tailspin
Tailspin uses streams of values within streams of values rather than loops.
1..5 -> '$:1..$ -> '*';
' -> !OUT::write
- Output:
* ** *** **** *****
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)
TI-83 BASIC
For loops in TI-83 BASIC take at least 3 arguments, with an optional fourth: For(variable,start,end[,step]. Parentheses don't need to be closed in TI-BASIC.
ClrHome For(I,1,5 For(J,1,I Output(I,J,"* End End
TI-89 BASIC
Local i,j
ClrIO
For i, 1, 5
For j, 1, i
Output i*8, j*6, "*"
EndFor
EndFor
TorqueScript
for(%i = 0; %i < 5; %i++)
{
for(%x = %i; %x < 5; %x++)
{
%string = %string @ "*";
echo(%string);
}
}
TransFORTH
: PRINTSTARS ( ROWS -- )
1 + 1 DO
I 0 DO
PRINT " * " LOOP
CR LOOP ;
5 PRINTSTARS
TUSCRIPT
$$ MODE TUSCRIPT
m=""
LOOP n=1,5
m=APPEND (m,"","*")
PRINT m
ENDLOOP
- Output:
* ** *** **** *****
TypeScript
for (let i: number = 0; i < 5; ++i) {
let line: string = ""
for(let j: number = 0; j <= i; ++j) {
line += "*"
}
console.log(line)
}
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 "*"
.)
#!/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.
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.
for (( x=1; $x<=5; x=$x+1 )); do
for (( y=1; y<=$x; y=$y+1 )); do
echo -n '*'
done
echo ""
done
C Shell
foreach i (`jot 5`)
foreach j (`jot $i`)
echo -n \*
end
echo ""
end
ksh
for ((x = 1; x <= 5; x += 1))
do
for ((y = 0; y < x; y += 1))
do
print -n '*'
done
print
done
UnixPipes
yes \ | cat -n | (while read n ; do
[ $n -gt 5 ] && exit 0;
yes \* | head -n $n | xargs -n $n echo
done)
Ursa
#
# for loop
#
decl int i j
for (set i 0) (< i 5) (inc i)
for (set j 0) (< j (int (+ i 1))) (inc j)
out "*" console
end for
out endl console
end for
Vala
int main (string[] args) {
for (var i = 1; i <= 5; i++) {
for (var j = 1; j <= i; j++) {
stdout.putc ('*');
}
stdout.putc ('\n');
}
return 0;
}
VBA
Option Explicit
Sub LoopEx()
Dim i As Long, j As Long, s As String
For i = 1 To 5
s = ""
For j = 1 To i
s = s + "*"
Next
Debug.Print s
Next
End Sub
VBScript
Option Explicit
Dim i, j, s
For i = 1 To 5
s = ""
For j = 1 To i
s = s + "*"
Next
WScript.Echo s
Next
Vedit macro language
for (#1 = 1; #1 <= 5; #1++) {
for (#2 = 1; #2 <= #1; #2++) {
Type_Char('*')
}
Type_Newline
}
Verilog
module main;
integer i, j;
initial begin
for(i = 1; i <= 5; i = i + 1) begin
for(j = 1; j <= i; j = j + 1) $write("*");
$display("");
end
$finish ;
end
endmodule
Vim Script
The two-loop approach determined in the description is solved in a similar manner to Python (initial solution) and Nim, using the inbuilt function, range(), which technically may be considered a for each loop. Nonetheless, it is an incrementing integer solution like many others provided. The script will append the output to the end of the current buffer. It uses inbuilt functions append(), line(), setline(), and getline():
for i in range(1, 5)
call append(line('$'), '')
for j in range(1, i)
call setline(line('$'), getline('$') .. '*')
endfor
endfor
If the constraint to use two for loops was absent, the more concise Vim Script solution ― similar to idiomatic Python solution #2 ― would be (this time using builtin functions echoc[onsole] and repeat() to demonstrate another approach to generating the output, i.e., to the console):
for i in range(1, 5)
echoc repeat('*', i)
endfor
V (Vlang)
fn main() {
for i in 1..6 {
for _ in 1..i+1 {
print("*")
}
print("\n")
}
}
- Output:
* ** *** **** *****
Wart
for i 1 (i <= 5) ++i
for j 0 (j < i) ++j
pr "*"
(prn)
Wee Basic
print 1 "" ensures the end of program text is separate from the asterisk characters.
for y=0 to 4
print 1 ""
for x=0 to y
print 1 at x,y "*"
next
next
end
Wren
for (i in 1..5) {
for (j in 1..i) System.write("*")
System.print()
}
- Output:
* ** *** **** *****
x86 Assembly
This subroutine uses only the original 16-bit 8086 instruction set; it is written for DOS, but could be adapted to run under other operating systems.
loops: mov bx, 1 ; outer loop counter
outerloop: mov cx, bx ; inner loop counter
mov dl, 42 ; '*' character
innerloop: mov ah, 6
int 21h ; print
dec cx
jcxz innerdone
jmp innerloop
innerdone: mov dl, 10 ; newline
mov ah, 6
int 21h
inc bx
cmp bx, 6
jne outerloop
ret
XBasic
PROGRAM "for"
DECLARE FUNCTION Entry()
FUNCTION Entry()
FOR i% = 1 TO 5
FOR j% = 1 TO i%
PRINT "*";
NEXT j%
PRINT
NEXT i%
END FUNCTION
END PROGRAM
XBS
const repChar:string = "*";
const maxIters = 5;
for(i=1;maxIters;1){
set str:string = "";
for(o=1;i;1){
str+=repChar;
}
log(str);
}
- Output:
* ** *** **** *****
XLISP
The equivalent of other languages' FOR or DO loops can be written using DO:
(DO ((I 1 (+ I 1))) ((> I 5))
(DO ((J 0 (+ J 1))) ((= J I))
(DISPLAY "*"))
(NEWLINE))
- Output:
* ** *** **** *****
This construct is not, however, very idiomatic: loops in XLISP are mostly written using recursion.
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);
]
Z80 Assembly
For the Amstrad CPC (should work with e.g. the built-in assembler in JavaCPC; use call &4000 to start from BASIC):
org &4000 ; put code at memory address 0x4000
wr_char equ &bb5a ; write ASCII character in register A to screen
; (jumps into CPC ROM)
; put registers on stack so we can return to BASIC later
push bc
push de
push hl
ld b,5 ; loop from 5 to 1
row:
push bc ; save outer loop variable
; calculate inner loop limit (6 - outer loop variable)
ld a,6
sub b
ld b,a
column:
ld a,42 ; asterisk in ASCII
call wr_char
djnz column ; decrement B, jump to label if non-zero
pop bc ; restore outer loop
; print carriage return/line feed
ld a,13
call wr_char
ld a,10
call wr_char
djnz row
; restore registers
pop hl
pop de
pop bc
ret ; return to BASIC interpreter
Zig
const std = @import("std");
pub fn main() !void {
const stdout_wr = std.io.getStdOut().writer();
for (1..6) |n| {
for (0..n) |_| {
try stdout_wr.writeAll("*");
}
try stdout_wr.writeAll("\n");
}
}
- Output:
* ** *** **** *****
zkl
foreach i in ([1..5]){
foreach j in (i){print("*")}
println();
}
- Output:
* ** *** **** *****
- Programming Tasks
- Iteration
- Simple
- GUISS/Omit
- 11l
- 360 Assembly
- 68000 Assembly
- 8086 Assembly
- 8th
- AArch64 Assembly
- Action!
- ActionScript
- Ada
- Agena
- ALGOL 60
- ALGOL 68
- ALGOL W
- ALGOL-M
- Alore
- AmigaE
- Apex
- APL
- AppleScript
- ARM Assembly
- Arturo
- Asymptote
- AutoHotkey
- Avail
- AWK
- Axe
- Babel
- Bait
- Bash
- BASIC
- Applesoft BASIC
- BASIC256
- BaCon
- BBC BASIC
- Chipmunk Basic
- Commodore BASIC
- Creative Basic
- GW-BASIC
- FBSL
- FUZE BASIC
- IS-BASIC
- IWBASIC
- Liberty BASIC
- MSX Basic
- Microsoft Small Basic
- PureBasic
- QBasic
- Quite BASIC
- Run BASIC
- SmallBASIC
- Smart BASIC
- True BASIC
- Visual Basic
- Visual Basic .NET
- Yabasic
- ZX Spectrum Basic
- Batch File
- Bc
- BCPL
- Befunge
- Binary Lambda Calculus
- Blz
- Bracmat
- Brainf***
- Brat
- C
- C sharp
- C++
- C3
- Ceylon
- Chapel
- Chef
- Clojure
- CLU
- COBOL
- ColdFusion
- Common Lisp
- Coq
- Cowgol
- Crystal
- D
- Dao
- Dart
- Dc
- Delphi
- Diego
- DMS
- Dodo0
- Draco
- Dragon
- DWScript
- Dyalect
- E
- EasyLang
- Ed
- EDSAC order code
- EGL
- Ela
- Elena
- Elixir
- Emacs Lisp
- EMal
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- FALSE
- Fantom
- Fennel
- Fermat
- FOCAL
- Forth
- Fortran
- FreeBASIC
- Frink
- Futhark
- Futhark examples needing attention
- Examples needing attention
- FutureBasic
- Gambas
- GAP
- GML
- Go
- Groovy
- Hack
- Haskell
- Haxe
- Hexiscript
- HicEst
- HolyC
- Icon
- Unicon
- Inform 7
- J
- Java
- JavaScript
- Jinja
- Jq
- Jsish
- Julia
- Klong
- Kotlin
- LabVIEW
- Lambdatalk
- Lang5
- Langur
- Lasso
- LC3 Assembly
- LDPL
- LIL
- Lingo
- Lisaac
- LiveCode
- Logo
- Lua
- M2000 Interpreter
- M4
- Make
- Jot
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- MAXScript
- Mercury
- MiniScript
- MIPS Assembly
- Modula-2
- Modula-3
- MOO
- Morfa
- MUMPS
- Nanoquery
- Nemerle
- NetRexx
- NewLISP
- Nim
- NS-HUBASIC
- Nu
- Oberon-2
- Objeck
- OCaml
- Odin
- Oforth
- Onyx
- Order
- Oz
- Panoramic
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phixmonti
- PHP
- Picat
- PicoLisp
- Pike
- PILOT
- PL/I
- Plain English
- Pop11
- PowerShell
- Processing
- Prolog
- Python
- QB64
- Quackery
- R
- Racket
- Raku
- Rapira
- REBOL
- Red
- ReScript
- Retro
- REXX
- Ring
- RPL
- Ruby
- Rust
- Salmon
- SAS
- Sather
- Scala
- Scheme
- Scilab
- Seed7
- SETL
- Sidef
- Simula
- Slate
- Smalltalk
- SNOBOL4
- SNUSP
- Sparkling
- Spin
- SPL
- Stata
- Suneido
- Swift
- Tailspin
- Tcl
- TI-83 BASIC
- TI-89 BASIC
- TorqueScript
- TransFORTH
- TUSCRIPT
- TypeScript
- UNIX Shell
- C Shell
- Ksh
- UnixPipes
- Ursa
- Vala
- VBA
- VBScript
- Vedit macro language
- Verilog
- Vim Script
- V (Vlang)
- Wart
- Wee Basic
- Wren
- X86 Assembly
- XBasic
- XBS
- XLISP
- XPL0
- Z80 Assembly
- Zig
- Zkl
- Pages with too many expensive parser function calls