Loops/N plus one half: Difference between revisions
PascalABC.NET |
|||
(92 intermediate revisions by 48 users not shown) | |||
Line 3: | Line 3: | ||
Quite often one needs loops which, in the last iteration, execute only part of the loop body. |
Quite often one needs loops which, in the last iteration, execute only part of the loop body. |
||
;Goal: |
;Goal: |
||
Demonstrate the best way to do this. |
Demonstrate the best way to do this. |
||
;Task: |
;Task: |
||
Line 15: | Line 13: | ||
and the comma from within the body of the loop. |
and the comma from within the body of the loop. |
||
;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]] |
|||
=={{header|11l}}== |
|||
;Related tasks: |
|||
<syntaxhighlight lang="11l"> |
|||
* [[Loop over multiple arrays simultaneously]] |
|||
L(i) 1..10 |
|||
* [[Loops/Break]] |
|||
print(i, end' ‘’) |
|||
* [[Loops/Continue]] |
|||
I !L.last_iteration |
|||
* [[Loops/Do-while]] |
|||
print(‘, ’, end' ‘’) |
|||
* [[Loops/Downward for]] |
|||
</syntaxhighlight> |
|||
* [[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]] |
|||
* [[Loops/Wrong ranges]] |
|||
<br><br> |
|||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm"> |
||
* Loops/N plus one half 13/08/2015 |
* Loops/N plus one half 13/08/2015 |
||
LOOPHALF CSECT USING LOOPHALF,R12 |
LOOPHALF CSECT USING LOOPHALF,R12 |
||
Line 60: | Line 63: | ||
YREGS |
YREGS |
||
END LOOPHALF |
END LOOPHALF |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 66: | Line 69: | ||
</pre> |
</pre> |
||
=={{header|68000 Assembly}}== |
|||
Sega Genesis cartridge header and hardware print routines/bitmap font are omitted here but do work as intended. |
|||
<syntaxhighlight lang="68000devpac"> |
|||
moveq #0,d0 |
|||
move.w #1,d1 ;ABCD can't use an immediate operand |
|||
move.w #10-1,d2 |
|||
loop: |
|||
abcd d1,d0 |
|||
move.l d0,-(sp) |
|||
jsr printhex |
|||
move.l (sp)+,d0 |
|||
cmp.b #$10,d0 ;we use hex 10 since this is binary-coded decimal |
|||
beq exitEarly |
|||
move.l d0,-(sp) |
|||
move.b #',',D0 ;PrintChar uses D0 as input |
|||
jsr PrintChar |
|||
move.b #' ',D0 |
|||
jsr PrintChar |
|||
move.l (sp)+,d0 |
|||
DBRA d2,loop |
|||
exitEarly: |
|||
; include "X:\SrcGEN\testModule.asm" |
|||
jmp * |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>01, 02, 03, 04, 05, 06, 07, 08, 09, 10</pre> |
|||
=={{header|8086 Assembly}}== |
|||
Since the output of the last element is different than the rest, the easiest way to accomplish this is by "breaking out" of the loop with a comparison to 10. |
|||
<syntaxhighlight lang="asm"> |
|||
.model small |
|||
.stack 1024 |
|||
.data ;no data needed |
|||
.code |
|||
start: |
|||
mov ax,0000h |
|||
mov cx,0FFFFh ;this value doesn't matter as long as it's greater than decimal 10. |
|||
repeatPrinting: |
|||
add ax,1 ;it was easier to start at zero and add here than to start at 1 and add after printing. |
|||
aaa ;ascii adjust for addition, corrects 0009h+1 from 000Ah to 0100h |
|||
call PrintBCD_IgnoreLeadingZeroes |
|||
cmp ax,0100h ;does AX = BCD 10? |
|||
je exitLoopEarly ;if so, we're done now. Don't finish the loop. |
|||
push ax |
|||
mov dl,"," ;print a comma |
|||
mov ah,02h |
|||
int 21h |
|||
mov dl,20h ;print a blank space |
|||
mov ah,02h |
|||
int 21h |
|||
pop ax |
|||
loop repeatPrinting |
|||
exitLoopEarly: |
|||
mov ax,4C00h |
|||
int 21h ;return to DOS |
|||
PrintBCD_IgnoreLeadingZeroes: |
|||
push ax |
|||
cmp ah,0 |
|||
jz skipLeadingZero |
|||
or ah,30h ;converts a binary-coded-decimal value to an ASCII numeral |
|||
push dx |
|||
push ax |
|||
mov al,ah |
|||
mov ah,0Eh |
|||
int 10h ;prints AL to screeen |
|||
pop ax |
|||
pop dx |
|||
skipLeadingZero: |
|||
or al,30h |
|||
push dx |
|||
push ax |
|||
mov ah,0Eh |
|||
int 10h ;prints AL to screen |
|||
pop ax |
|||
pop dx |
|||
pop ax |
|||
ret |
|||
end start ;EOF |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|AArch64 Assembly}}== |
|||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
|||
<syntaxhighlight lang="aarch64 assembly"> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
|||
/* program loopnplusone64.s */ |
|||
/*******************************************/ |
|||
/* Constantes file */ |
|||
/*******************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly*/ |
|||
.include "../includeConstantesARM64.inc" |
|||
/*********************************/ |
|||
/* Initialized data */ |
|||
/*********************************/ |
|||
.data |
|||
szMessResult: .asciz "@" // message result |
|||
szMessComma: .asciz ", " |
|||
szCarriageReturn: .asciz "\n" |
|||
/*********************************/ |
|||
/* UnInitialized data */ |
|||
/*********************************/ |
|||
.bss |
|||
sZoneConv: .skip 24 |
|||
/*********************************/ |
|||
/* code section */ |
|||
/*********************************/ |
|||
.text |
|||
.global main |
|||
main: // entry of program |
|||
mov x20,1 // loop counter |
|||
1: // begin loop |
|||
mov x0,x20 |
|||
ldr x1,qAdrsZoneConv // display value |
|||
bl conversion10 // decimal conversion |
|||
ldr x0,qAdrszMessResult |
|||
ldr x1,qAdrsZoneConv // display value |
|||
bl strInsertAtCharInc // insert result at @ character |
|||
bl affichageMess // display message |
|||
ldr x0,qAdrszMessComma |
|||
bl affichageMess // display comma |
|||
add x20,x20,1 // increment counter |
|||
cmp x20,10 // end ? |
|||
blt 1b // no ->begin loop one |
|||
mov x0,x20 |
|||
ldr x1,qAdrsZoneConv // display value |
|||
bl conversion10 // decimal conversion |
|||
ldr x0,qAdrszMessResult |
|||
ldr x1,qAdrsZoneConv // display value |
|||
bl strInsertAtCharInc // insert result at @ character |
|||
bl affichageMess // display message |
|||
ldr x0,qAdrszCarriageReturn |
|||
bl affichageMess // display return line |
|||
100: // standard end of the program |
|||
mov x0,0 // return code |
|||
mov x8,EXIT // request to exit program |
|||
svc 0 // perform the system call |
|||
qAdrsZoneConv: .quad sZoneConv |
|||
qAdrszMessResult: .quad szMessResult |
|||
qAdrszMessComma: .quad szMessComma |
|||
qAdrszCarriageReturn: .quad szCarriageReturn |
|||
/********************************************************/ |
|||
/* File Include fonctions */ |
|||
/********************************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly */ |
|||
.include "../includeARM64.inc" |
|||
</syntaxhighlight> |
|||
{{Output}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
ACL2 does not have loops, but this is close: |
ACL2 does not have loops, but this is close: |
||
<syntaxhighlight lang="lisp"> |
|||
<lang Lisp>(defun print-list (xs) |
|||
(defun print-list (xs) |
|||
(progn$ (cw "~x0" (first xs)) |
(progn$ (cw "~x0" (first xs)) |
||
(if (endp (rest xs)) |
(if (endp (rest xs)) |
||
(cw (coerce '(#\Newline) 'string)) |
(cw (coerce '(#\Newline) 'string)) |
||
(progn$ (cw ", ") |
(progn$ (cw ", ") |
||
(print-list (rest xs)))))) |
(print-list (rest xs)))))) |
||
</syntaxhighlight> |
|||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">PROC Main() |
|||
BYTE i=[1] |
|||
DO |
|||
PrintB(i) |
|||
IF i=10 THEN |
|||
EXIT |
|||
FI |
|||
Print(", ") |
|||
i==+1 |
|||
OD |
|||
RETURN |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/N_plus_one_half.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
<syntaxhighlight lang="ada"> |
|||
<lang ada>with Ada.Text_IO; |
|||
with Ada.Text_IO; |
|||
procedure LoopsAndHalf is |
procedure LoopsAndHalf is |
||
Line 88: | Line 282: | ||
end loop; |
end loop; |
||
Ada.Text_IO.new_line; |
Ada.Text_IO.new_line; |
||
end LoopsAndHalf; |
end LoopsAndHalf; |
||
</syntaxhighlight> |
|||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
<lang |
<syntaxhighlight lang="aime"> |
||
integer i; |
|||
i = 0; |
i = 0; |
||
Line 102: | Line 298: | ||
o_text(", "); |
o_text(", "); |
||
} |
} |
||
o_text("\n"); |
o_text("\n"); |
||
</syntaxhighlight> |
|||
=={{header|ALGOL 60}}== |
=={{header|ALGOL 60}}== |
||
{{works with|ALGOL 60|OS/360}} |
{{works with|ALGOL 60|OS/360}} |
||
< |
<syntaxhighlight lang="algol60"> |
||
'BEGIN' |
|||
'COMMENT' Loops N plus one half - Algol60 - 20/06/2018; |
'COMMENT' Loops N plus one half - Algol60 - 20/06/2018; |
||
'INTEGER' I; |
'INTEGER' I; |
||
Line 113: | Line 311: | ||
'IF' I 'NOTEQUAL' 10 'THEN' OUTSTRING(1,'(', ')') |
'IF' I 'NOTEQUAL' 10 'THEN' OUTSTRING(1,'(', ')') |
||
'END' |
'END' |
||
'END' |
'END' |
||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 125: | Line 324: | ||
There are three common ways of achieving n+½ loops: |
There are three common ways of achieving n+½ loops: |
||
{|border="1" style="border-collapse: collapse;" |
{|border="1" style="border-collapse: collapse;" |
||
||<lang |
||<syntaxhighlight lang="algol68"> |
||
FOR i WHILE |
|||
print(whole(i, -2)); |
print(whole(i, -2)); |
||
# WHILE # i < 10 DO |
# WHILE # i < 10 DO |
||
Line 132: | Line 332: | ||
OD; |
OD; |
||
print(new line) |
print(new line) |
||
</syntaxhighlight> |
|||
||<lang algol68>FOR i TO 10 DO |
|||
||<syntaxhighlight lang="algol68"> |
|||
FOR i TO 10 DO |
|||
print(whole(i, -2)); |
print(whole(i, -2)); |
||
IF i < 10 THEN |
IF i < 10 THEN |
||
Line 140: | Line 342: | ||
OD; |
OD; |
||
print(new line) |
print(new line) |
||
</syntaxhighlight> |
|||
||<lang algol68>FOR i DO |
|||
||<syntaxhighlight lang="algol68"> |
|||
FOR i DO |
|||
print(whole(i, -2)); |
print(whole(i, -2)); |
||
IF i >= 10 THEN GO TO done FI; |
IF i >= 10 THEN GO TO done FI; |
||
Line 148: | Line 352: | ||
OD; |
OD; |
||
done: |
done: |
||
print(new line) |
print(new line) |
||
</syntaxhighlight> |
|||
|} |
|} |
||
Output for all cases above: |
Output for all cases above: |
||
Line 156: | Line 361: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw"> |
||
begin |
|||
integer i; |
integer i; |
||
i := 0; |
i := 0; |
||
Line 169: | Line 375: | ||
writeon( "," ) |
writeon( "," ) |
||
end |
end |
||
end. |
end. |
||
</syntaxhighlight> |
|||
=={{header|Amazing Hopper}}== |
|||
Six ways to do this task in Hopper flavour "Jambo": |
|||
<syntaxhighlight lang="c"> |
|||
#include <jambo.h> |
|||
Main |
|||
i=1 |
|||
Loop if ' Less equal (i,10)' |
|||
Set 'i', Print if ( #(i<10), ",","") |
|||
++i |
|||
Back |
|||
Prnl |
|||
Loop for ( i=1, #(i<=10), ++i ) |
|||
Set 'i', Print only if ( #(10-i), ",") |
|||
Next |
|||
Prnl |
|||
i=1 |
|||
Loop |
|||
Set 'i', Print only if ( #(10-i), ",") |
|||
++i |
|||
While ' #(i<=10) ' |
|||
Prnl |
|||
i=1 |
|||
Loop |
|||
Set 'i', Print only if ( #(10-i), ",") |
|||
++i |
|||
Until ' #(i>10) ' |
|||
Prnl |
|||
i=1 |
|||
Loop |
|||
Set 'i', and print it |
|||
Break if '#( !(10-i) )' |
|||
Set '","' |
|||
++i |
|||
Back |
|||
Prnl |
|||
/* assembler Hopper */ |
|||
i=1 |
|||
loop single: |
|||
{i,10,i} sub, do{{","}}, print |
|||
++i, {i,11}, jneq(loop single) |
|||
puts("\n") |
|||
End |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1,2,3,4,5,6,7,8,9,10 |
|||
1,2,3,4,5,6,7,8,9,10 |
|||
1,2,3,4,5,6,7,8,9,10 |
|||
1,2,3,4,5,6,7,8,9,10 |
|||
1,2,3,4,5,6,7,8,9,10 |
|||
1,2,3,4,5,6,7,8,9,10 |
|||
</pre> |
|||
=={{header|AmigaE}}== |
=={{header|AmigaE}}== |
||
<lang |
<syntaxhighlight lang="amigae"> |
||
PROC main() |
|||
DEF i |
DEF i |
||
FOR i := 1 TO 10 |
FOR i := 1 TO 10 |
||
Line 179: | Line 442: | ||
WriteF(', ') |
WriteF(', ') |
||
ENDFOR |
ENDFOR |
||
ENDPROC |
ENDPROC |
||
</syntaxhighlight> |
|||
=={{header|ARM Assembly}}== |
|||
{{works with|as|Raspberry Pi}} |
|||
<syntaxhighlight lang="arm assembly"> |
|||
/* ARM assembly Raspberry PI */ |
|||
/* program loopnplusone.s */ |
|||
/* Constantes */ |
|||
.equ STDOUT, 1 @ Linux output console |
|||
.equ EXIT, 1 @ Linux syscall |
|||
.equ WRITE, 4 @ Linux syscall |
|||
/*********************************/ |
|||
/* Initialized data */ |
|||
/*********************************/ |
|||
.data |
|||
szMessResult: .ascii "" @ message result |
|||
sMessValeur: .fill 11, 1, ' ' |
|||
szMessComma: .asciz "," |
|||
szCarriageReturn: .asciz "\n" |
|||
/*********************************/ |
|||
/* UnInitialized data */ |
|||
/*********************************/ |
|||
.bss |
|||
/*********************************/ |
|||
/* code section */ |
|||
/*********************************/ |
|||
.text |
|||
.global main |
|||
main: @ entry of program |
|||
mov r4,#1 @ loop counter |
|||
1: @ begin loop |
|||
mov r0,r4 |
|||
ldr r1,iAdrsMessValeur @ display value |
|||
bl conversion10 @ decimal conversion |
|||
ldr r0,iAdrszMessResult |
|||
bl affichageMess @ display message |
|||
ldr r0,iAdrszMessComma |
|||
bl affichageMess @ display comma |
|||
add r4,#1 @ increment counter |
|||
cmp r4,#10 @ end ? |
|||
blt 1b @ no ->begin loop one |
|||
mov r0,r4 |
|||
ldr r1,iAdrsMessValeur @ display value |
|||
bl conversion10 @ decimal conversion |
|||
ldr r0,iAdrszMessResult |
|||
bl affichageMess @ display message |
|||
ldr r0,iAdrszCarriageReturn |
|||
bl affichageMess @ display return line |
|||
100: @ standard end of the program |
|||
mov r0, #0 @ return code |
|||
mov r7, #EXIT @ request to exit program |
|||
svc #0 @ perform the system call |
|||
iAdrsMessValeur: .int sMessValeur |
|||
iAdrszMessResult: .int szMessResult |
|||
iAdrszMessComma: .int szMessComma |
|||
iAdrszCarriageReturn: .int szCarriageReturn |
|||
/******************************************************************/ |
|||
/* display text with size calculation */ |
|||
/******************************************************************/ |
|||
/* r0 contains the address of the message */ |
|||
affichageMess: |
|||
push {r0,r1,r2,r7,lr} @ save registres |
|||
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" |
|||
svc #0 @ call systeme |
|||
pop {r0,r1,r2,r7,lr} @ restaur registers */ |
|||
bx lr @ return |
|||
/******************************************************************/ |
|||
/* Converting a register to a decimal */ |
|||
/******************************************************************/ |
|||
/* r0 contains value and r1 address area */ |
|||
.equ LGZONECAL, 10 |
|||
conversion10: |
|||
push {r1-r4,lr} @ save registers |
|||
mov r3,r1 |
|||
mov r2,#LGZONECAL |
|||
1: @ start loop |
|||
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1 |
|||
add r1,#48 @ digit |
|||
strb r1,[r3,r2] @ store digit on area |
|||
sub r2,#1 @ previous position |
|||
cmp r0,#0 @ stop if quotient = 0 |
|||
bne 1b @ else loop |
|||
@ end replaces digit in front of area |
|||
mov r4,#0 |
|||
2: |
|||
ldrb r1,[r3,r2] |
|||
strb r1,[r3,r4] @ store in area begin |
|||
add r4,#1 |
|||
add r2,#1 @ previous position |
|||
cmp r2,#LGZONECAL @ end |
|||
ble 2b @ loop |
|||
mov r1,#0 @ final zero |
|||
strb r1,[r3,r4] |
|||
100: |
|||
pop {r1-r4,lr} @ restaur registres |
|||
bx lr @return |
|||
/***************************************************/ |
|||
/* division par 10 signé */ |
|||
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* |
|||
/* and http://www.hackersdelight.org/ */ |
|||
/***************************************************/ |
|||
/* r0 dividende */ |
|||
/* r0 quotient */ |
|||
/* r1 remainder */ |
|||
divisionpar10: |
|||
/* r0 contains the argument to be divided by 10 */ |
|||
push {r2-r4} @ save registers */ |
|||
mov r4,r0 |
|||
mov r3,#0x6667 @ r3 <- magic_number lower |
|||
movt r3,#0x6666 @ r3 <- magic_number upper |
|||
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) |
|||
mov r2, r2, ASR #2 @ r2 <- r2 >> 2 |
|||
mov r1, r0, LSR #31 @ r1 <- r0 >> 31 |
|||
add r0, r2, r1 @ r0 <- r2 + r1 |
|||
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 |
|||
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) |
|||
pop {r2-r4} |
|||
bx lr @ return |
|||
</syntaxhighlight> |
|||
=={{header|ArnoldC}}== |
|||
<syntaxhighlight lang="arnoldc"> |
|||
IT'S SHOWTIME |
|||
HEY CHRISTMAS TREE n |
|||
YOU SET US UP @NO PROBLEMO |
|||
HEY CHRISTMAS TREE lessThanTen |
|||
YOU SET US UP @NO PROBLEMO |
|||
STICK AROUND lessThanTen |
|||
TALK TO THE HAND n |
|||
GET TO THE CHOPPER lessThanTen |
|||
HERE IS MY INVITATION 10 |
|||
LET OFF SOME STEAM BENNET n |
|||
ENOUGH TALK |
|||
BECAUSE I'M GOING TO SAY PLEASE lessThanTen |
|||
TALK TO THE HAND ", " |
|||
YOU HAVE NO RESPECT FOR LOGIC |
|||
GET TO THE CHOPPER n |
|||
HERE IS MY INVITATION n |
|||
GET UP @NO PROBLEMO |
|||
ENOUGH TALK |
|||
CHILL |
|||
YOU HAVE BEEN TERMINATED |
|||
</syntaxhighlight> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol"> |
|||
print join.with:", " map 1..10 => [to :string] |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
=={{header|Asymptote}}== |
|||
<syntaxhighlight lang="Asymptote"> |
|||
for(int i = 1; i <= 10; ++i) { |
|||
write(i, suffix=none); |
|||
if(i < 10) write(", ", suffix=none); |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
<syntaxhighlight lang="autohotkey"> |
|||
<lang AutoHotkey>Loop, 9 ; loop 9 times |
|||
Loop, 9 ; loop 9 times |
|||
{ |
{ |
||
output .= A_Index ; append the index of the current loop to the output var |
output .= A_Index ; append the index of the current loop to the output var |
||
Line 188: | Line 630: | ||
output .= ", " ; append ", " to the output var |
output .= ", " ; append ", " to the output var |
||
} |
} |
||
MsgBox, %output% |
MsgBox, %output% |
||
</syntaxhighlight> |
|||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
<syntaxhighlight lang="autoit"> |
|||
<lang autoit>#cs ---------------------------------------------------------------------------- |
|||
#cs ---------------------------------------------------------------------------- |
|||
AutoIt Version: 3.3.8.1 |
AutoIt Version: 3.3.8.1 |
||
Line 216: | Line 660: | ||
EndFunc |
EndFunc |
||
main() |
main() |
||
</syntaxhighlight> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
'''One-liner:''' |
'''One-liner:''' |
||
<syntaxhighlight lang="awk"> |
|||
<lang awk>$ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf ", "};print}'</lang> |
|||
$ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf ", "};print}' |
|||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 226: | Line 673: | ||
'''Readable version:''' |
'''Readable version:''' |
||
< |
<syntaxhighlight lang="awk"> |
||
BEGIN { |
BEGIN { |
||
n=10 |
n=10 |
||
Line 234: | Line 681: | ||
} |
} |
||
print |
print |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
Same output. |
Same output. |
||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
<syntaxhighlight lang="axe"> |
|||
<lang axe>For(I,1,10) |
|||
For(I,1,10) |
|||
Disp I▶Dec |
Disp I▶Dec |
||
If I=10 |
If I=10 |
||
Line 245: | Line 694: | ||
Disp "," |
Disp "," |
||
End |
End |
||
End |
End |
||
</syntaxhighlight> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|FreeBASIC}} |
{{works with|FreeBASIC}} |
||
{{works with|QBasic|1.1}} |
|||
{{works with|QuickBasic|4.5}} |
|||
{{works with|RapidQ}} |
{{works with|RapidQ}} |
||
<lang |
<syntaxhighlight lang="qbasic"> |
||
DIM i AS Integer |
|||
FOR i=1 TO 10 |
FOR i=1 TO 10 |
||
PRINT i; |
PRINT USING "##"; i; |
||
IF i=10 THEN EXIT FOR |
IF i=10 THEN EXIT FOR |
||
PRINT ", "; |
PRINT ", "; |
||
NEXT i |
NEXT i |
||
</syntaxhighlight> |
|||
=== |
==={{header|Applesoft BASIC}}=== |
||
{{works with|Commodore BASIC}} |
{{works with|Commodore BASIC}} |
||
The [[#ZX_Spectrum_Basic|ZX Spectrum Basic]] code will work just fine in Applesoft BASIC. The following is a more structured approach which avoids the use of GOTO. |
The [[#ZX_Spectrum_Basic|ZX Spectrum Basic]] code will work just fine in Applesoft BASIC. The following is a more structured approach which avoids the use of GOTO. |
||
<syntaxhighlight lang="applesoftbasic"> |
|||
10 FOR I = 1 TO 10 |
|||
20 PRINT I; |
20 PRINT I; |
||
30 IF I < 10 THEN PRINT ", "; : NEXT I |
30 IF I < 10 THEN PRINT ", "; : NEXT I |
||
</syntaxhighlight> |
|||
==={{header|ASIC}}=== |
|||
If equality checking affect the efficiency or if the last value were treated in different manner, one can extract the last iteration. |
|||
ASIC prints integer numbers as six-char strings. If shorter ones are needed, one can use the <code>STR$</code> and <code>LTRIM$</code> functions. |
|||
<syntaxhighlight lang="basic"> |
|||
REM Loops/N plus one half |
|||
FOR I = 1 TO 9 |
|||
PRINT I; |
|||
PRINT ","; |
|||
NEXT I |
|||
PRINT 10 |
|||
END |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
==={{header|Basic09}}=== |
|||
<syntaxhighlight lang="basic09"> |
|||
PROCEDURE nAndAHalf |
|||
DIM i:INTEGER |
|||
FOR i:=1 TO 10 |
|||
PRINT i; |
|||
EXITIF i=10 THEN ENDEXIT |
|||
PRINT ", "; |
|||
NEXT i |
|||
PRINT |
|||
</syntaxhighlight> |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="basic256"> |
|||
for i = 1 to 10 |
|||
print i; |
|||
if i < 10 then print ", "; |
|||
next i |
|||
end |
|||
</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
|||
<syntaxhighlight lang="bbcbasic"> |
|||
FOR i% = 1 TO 10 |
|||
PRINT ; i% ; |
|||
IF i% <> 10 PRINT ", "; |
|||
NEXT |
|||
PRINT |
|||
</syntaxhighlight> |
|||
==={{header|bootBASIC}}=== |
|||
There are no for/next or do/while loops in bootBASIC. Only goto. |
|||
<syntaxhighlight lang="BASIC"> |
|||
10 a=1 |
|||
20 print a ; |
|||
30 if a-10 goto 100 |
|||
40 goto 130 |
|||
100 print ", "; |
|||
110 a=a+1 |
|||
120 goto 20 |
|||
130 print |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
==={{header|Chipmunk Basic}}=== |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
<syntaxhighlight lang="qbasic"> |
|||
10 rem Loops/N plus one half |
|||
20 c$ = "" |
|||
30 for i = 1 to 10 |
|||
40 print c$;str$(i); |
|||
50 c$ = ", " |
|||
60 next i |
|||
</syntaxhighlight> |
|||
==={{header|FBSL}}=== |
|||
<syntaxhighlight lang="qbasic"> |
|||
#APPTYPE CONSOLE |
|||
For Dim i = 1 To 10 |
|||
PRINT i; |
|||
IF i < 10 THEN PRINT ", "; |
|||
Next |
|||
PAUSE |
|||
</syntaxhighlight> |
|||
Output |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
Press any key to continue...</pre> |
|||
==={{header|FreeBASIC}}=== |
|||
<syntaxhighlight lang="freebasic"> |
|||
' FB 1.05.0 Win64 |
|||
For i As Integer = 1 To 10 |
|||
Print Str(i); |
|||
If i < 10 Then Print ", "; |
|||
Next |
|||
Print |
|||
Sleep |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
====Alternative==== |
|||
This makes the important point that for many loops of this kind the partial iteration could easily be the ''first'' one. |
|||
<syntaxhighlight lang="freebasic"> |
|||
dim as string cm = "" |
|||
for i as ubyte = 1 to 10 |
|||
print cm;str(i); |
|||
cm = ", " |
|||
next i |
|||
</syntaxhighlight> |
|||
==={{header|FutureBasic}}=== |
|||
<syntaxhighlight lang="futurebasic"> |
|||
window 1 |
|||
long i, num = 10 |
|||
for i = 1 to num |
|||
print i; |
|||
if i = num then break |
|||
print @", "; |
|||
next i |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
==={{header|Gambas}}=== |
|||
'''[https://gambas-playground.proko.eu/?gist=c43cc581e5f93e70c5dc82733f609a7e Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas"> |
|||
Public Sub Main() |
|||
Dim siLoop As Short |
|||
For siLoop = 1 To 10 |
|||
Print siLoop; |
|||
If siLoop <> 10 Then Print ", "; |
|||
Next |
|||
End |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
==={{header|GW-BASIC}}=== |
|||
<syntaxhighlight lang="gwbasic"> |
|||
10 C$ = "" |
|||
20 FOR I = 1 TO 10 |
|||
30 PRINT C$;STR$(I); |
|||
40 C$=", " |
|||
50 NEXT I |
|||
</syntaxhighlight> |
|||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
<syntaxhighlight lang="is-basic"> |
|||
<lang IS-BASIC>100 FOR I=1 TO 10 |
|||
100 FOR I=1 TO 10 |
|||
110 PRINT I; |
110 PRINT I; |
||
120 IF I=10 THEN EXIT FOR |
120 IF I=10 THEN EXIT FOR |
||
130 PRINT ","; |
130 PRINT ","; |
||
140 NEXT |
140 NEXT |
||
</syntaxhighlight> |
|||
==={{header|Liberty BASIC}}=== |
|||
{{works with|Just BASIC}} |
|||
Keyword 'exit' allows the termination. |
|||
<syntaxhighlight lang="lb"> |
|||
for i =1 to 10 |
|||
print i; |
|||
if i =10 then exit for |
|||
print ", "; |
|||
next i |
|||
end |
|||
</syntaxhighlight> |
|||
==={{header|Microsoft Small Basic}}=== |
|||
<syntaxhighlight lang="smallbasic"> |
|||
For i = 1 To 10 |
|||
TextWindow.Write(i) |
|||
If i <> 10 Then |
|||
TextWindow.Write(", ") |
|||
EndIf |
|||
EndFor |
|||
TextWindow.WriteLine("") |
|||
</syntaxhighlight> |
|||
==={{header|NS-HUBASIC}}=== |
|||
<syntaxhighlight lang="ns-hubasic"> |
|||
10 FOR I=1 TO 10 |
|||
20 PRINT I; |
|||
30 IF I=10 THEN GOTO 50 |
|||
40 PRINT ","; |
|||
50 NEXT |
|||
</syntaxhighlight> |
|||
==={{header|PureBasic}}=== |
|||
<syntaxhighlight lang="purebasic"> |
|||
x=1 |
|||
Repeat |
|||
Print(Str(x)) |
|||
x+1 |
|||
If x>10: Break: EndIf |
|||
Print(", ") |
|||
ForEver |
|||
</syntaxhighlight> |
|||
==={{header|QBasic}}=== |
|||
{{works with|QBasic|1.1}} |
|||
{{works with|QuickBasic|4.5}} |
|||
<syntaxhighlight lang="qbasic"> |
|||
FOR i = 1 TO 10 |
|||
PRINT USING "##"; i; |
|||
IF i=10 THEN EXIT FOR |
|||
PRINT ", "; |
|||
NEXT i |
|||
</syntaxhighlight> |
|||
==={{header|Run BASIC}}=== |
|||
<syntaxhighlight lang="runbasic"> |
|||
FOR i = 1 TO 10 |
|||
PRINT cma$;i; |
|||
cma$ = ", " |
|||
NEXT i |
|||
</syntaxhighlight> |
|||
==={{header|Sinclair ZX81 BASIC}}=== |
==={{header|Sinclair ZX81 BASIC}}=== |
||
The [[#ZX_Spectrum_Basic|ZX Spectrum Basic]] program will work on the ZX81. Depending on the context, the programmer's intention may be clearer if we do it all with <code>GOTO</code>s instead of a <code>FOR</code> loop. |
The [[#ZX_Spectrum_Basic|ZX Spectrum Basic]] program will work on the ZX81. Depending on the context, the programmer's intention may be clearer if we do it all with <code>GOTO</code>s instead of a <code>FOR</code> loop. |
||
<lang |
<syntaxhighlight lang="basic"> |
||
10 LET I=1 |
|||
20 PRINT I; |
20 PRINT I; |
||
30 IF I=10 THEN GOTO 70 |
30 IF I=10 THEN GOTO 70 |
||
40 PRINT ", "; |
40 PRINT ", "; |
||
50 LET I=I+1 |
50 LET I=I+1 |
||
60 GOTO 20 |
60 GOTO 20 |
||
</syntaxhighlight> |
|||
=== |
==={{header|TI-89 BASIC}}=== |
||
There is no horizontal cursor position on the program IO screen, so we concatenate strings instead. |
|||
<syntaxhighlight lang="ti89b"> |
|||
Local str |
|||
"" → str |
|||
For i,1,10 |
|||
str & string(i) → str |
|||
If i < 10 Then |
|||
str & "," → str |
|||
EndIf |
|||
EndFor |
|||
Disp str |
|||
</syntaxhighlight> |
|||
==={{header|Tiny BASIC}}=== |
|||
Tiny BASIC does not support string concatenation so each number is on a separate line but this is at least in the spirit of the task description. |
|||
<syntaxhighlight lang="tinybasic"> |
|||
LET I = 1 |
|||
10 IF I = 10 THEN PRINT I |
|||
IF I < 10 THEN PRINT I,", " |
|||
IF I = 10 THEN END |
|||
LET I = I + 1 |
|||
GOTO 10 |
|||
</syntaxhighlight> |
|||
A solution for the dialects of Tiny BASIC that support string concatenation. |
|||
{{works with|TinyBasic}} |
|||
<syntaxhighlight lang="basic"> |
|||
10 REM Loops/N plus one half |
|||
20 LET I = 1 |
|||
30 IF I = 10 THEN PRINT I |
|||
40 IF I < 10 THEN PRINT I; ", "; |
|||
50 IF I = 10 THEN END |
|||
60 LET I = I + 1 |
|||
70 GOTO 30 |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
==={{header|True BASIC}}=== |
|||
{{works with|QBasic}} |
|||
<syntaxhighlight lang="qbasic"> |
|||
LET cm$ = "" |
|||
FOR i = 1 to 10 |
|||
PRINT cm$; str$(i); |
|||
LET cm$ = ", " |
|||
NEXT i |
|||
END |
|||
</syntaxhighlight> |
|||
==={{header|VBA}}=== |
|||
<syntaxhighlight lang="vb"> |
|||
Public Sub WriteACommaSeparatedList() |
|||
Dim i As Integer |
|||
Dim a(1 To 10) As String |
|||
For i = 1 To 10 |
|||
a(i) = CStr(i) |
|||
Next i |
|||
Debug.Print Join(a, ", ") |
|||
End Sub |
|||
</syntaxhighlight> |
|||
==={{header|Visual Basic .NET}}=== |
|||
<syntaxhighlight lang="vbnet"> |
|||
For i = 1 To 10 |
|||
Console.Write(i) |
|||
If i = 10 Then Exit For |
|||
Console.Write(", ") |
|||
Next |
|||
</syntaxhighlight> |
|||
==={{header|Wee Basic}}=== |
|||
print 1 "" ensures the end of program text is separate from the list of numbers. |
|||
<syntaxhighlight lang="wee basic"> |
|||
print 1 "" |
|||
for numbers=1 to 10 |
|||
print 1 at numbers*3-2,0 numbers |
|||
if numbers<>10 |
|||
print 1 at numbers*3-1,0 "," |
|||
endif |
|||
end |
|||
</syntaxhighlight> |
|||
==={{header|XBasic}}=== |
|||
{{works with|Windows XBasic}} |
|||
<syntaxhighlight lang="xbasic"> |
|||
PROGRAM "n_plus_one_half" |
|||
DECLARE FUNCTION Entry() |
|||
FUNCTION Entry() |
|||
FOR i% = 1 TO 10 |
|||
PRINT i%; |
|||
IF i% = 10 THEN EXIT FOR |
|||
PRINT ","; |
|||
NEXT i% |
|||
END FUNCTION |
|||
END PROGRAM |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
If equality checking affect the efficiency or if the last value were treated in different manner, one can extract the last iteration. |
|||
{{works with|Windows XBasic}} |
|||
<syntaxhighlight lang="xbasic"> |
|||
PROGRAM "n_plus_one_half" |
|||
DECLARE FUNCTION Entry() |
|||
FUNCTION Entry() |
|||
FOR i% = 1 TO 9 |
|||
PRINT i%; ","; |
|||
NEXT i% |
|||
PRINT 10 |
|||
END FUNCTION |
|||
END PROGRAM |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="yabasic"> |
|||
for i = 1 to 10 |
|||
print i; |
|||
if i < 10 print ", "; |
|||
next i |
|||
print |
|||
end |
|||
</syntaxhighlight> |
|||
==={{header|ZX Spectrum Basic}}=== |
|||
{{works with|Applesoft BASIC}} |
{{works with|Applesoft BASIC}} |
||
{{works with|Commodore BASIC}} |
{{works with|Commodore BASIC}} |
||
To terminate a loop on the ZX Spectrum, set the loop counter to a value that will exit the loop, before jumping to the NEXT statement. |
To terminate a loop on the ZX Spectrum, set the loop counter to a value that will exit the loop, before jumping to the NEXT statement. |
||
<syntaxhighlight lang="zxbasic"> |
|||
10 FOR i=1 TO 10 |
|||
20 PRINT i; |
20 PRINT i; |
||
30 IF i=10 THEN GOTO 50 |
30 IF i=10 THEN GOTO 50 |
||
40 PRINT ", "; |
40 PRINT ", "; |
||
50 NEXT i |
50 NEXT i |
||
</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
|||
<lang bbcbasic> FOR i% = 1 TO 10 |
|||
PRINT ; i% ; |
|||
IF i% <> 10 PRINT ", "; |
|||
NEXT |
|||
PRINT</lang> |
|||
=={{header|bc}}== |
=={{header|bc}}== |
||
{{Works with|GNU bc}} |
{{Works with|GNU bc}} |
||
The <code>print</code> extension is necessary to get the required output. |
The <code>print</code> extension is necessary to get the required output. |
||
<lang |
<syntaxhighlight lang="bc"> |
||
while (1) { |
|||
print ++i |
print ++i |
||
if (i == 10) { |
if (i == 10) { |
||
Line 311: | Line 1,123: | ||
} |
} |
||
print ", " |
print ", " |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
<lang |
<syntaxhighlight lang="befunge"> |
||
1+>::.9`#@_" ,",, |
|||
</syntaxhighlight> |
|||
This code is a good answer. However, most Befunge implementations print a " " after using . (output number), so this program prints "1 , 2 , 3 ..." with extra spaces. A bypass for this is possible, by adding 48 and printing the ascii character, but does not work with 10:: |
This code is a good answer. However, most Befunge implementations print a " " after using . (output number), so this program prints "1 , 2 , 3 ..." with extra spaces. A bypass for this is possible, by adding 48 and printing the ascii character, but does not work with 10:: |
||
<lang |
<syntaxhighlight lang="befunge"> |
||
1+>::68*+,8`#v_" ,",, |
|||
@,,,,", 10"<</lang> |
|||
@,,,,", 10"< |
|||
</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
<lang |
<syntaxhighlight lang="bracmat"> |
||
1:?i |
|||
& whl |
& whl |
||
' ( put$!i |
' ( put$!i |
||
& !i+1:~>10:?i |
& !i+1:~>10:?i |
||
& put$", " |
& put$", " |
||
) |
) |
||
</syntaxhighlight> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
{{trans|C++}} |
{{trans|C++}} |
||
<syntaxhighlight lang="c"> |
|||
<lang c>#include <stdio.h> |
|||
#include <stdio.h> |
|||
int main() |
int main() |
||
Line 339: | Line 1,159: | ||
} |
} |
||
return 0; |
return 0; |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|C++}}== |
|||
<lang cpp>#include <iostream> |
|||
int main() |
|||
{ |
|||
int i; |
|||
for (i = 1; i<10 ; i++) |
|||
std::cout << i << ", "; |
|||
std::cout<<i; |
|||
return 0; |
|||
}</lang> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
<lang |
<syntaxhighlight lang="csharp"> |
||
using System; |
|||
class Program |
class Program |
||
Line 368: | Line 1,178: | ||
Console.WriteLine(); |
Console.WriteLine(); |
||
} |
} |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|C++}}== |
|||
<syntaxhighlight lang="cpp"> |
|||
#include <iostream> |
|||
int main() |
|||
{ |
|||
int i; |
|||
for (i = 1; i<=10 ; i++){ |
|||
std::cout << i; |
|||
if (i < 10) |
|||
std::cout << ", "; |
|||
} |
|||
return 0; |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Chapel}}== |
=={{header|Chapel}}== |
||
<lang |
<syntaxhighlight lang="chapel"> |
||
for i in 1..10 do |
|||
write(i, if i % 10 > 0 then ", " else "\n")</lang> |
|||
write(i, if i % 10 > 0 then ", " else "\n") |
|||
</syntaxhighlight> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure"> |
||
; Functional version |
; Functional version |
||
(apply str (interpose ", " (range 1 11))) |
(apply str (interpose ", " (range 1 11))) |
||
Line 386: | Line 1,215: | ||
(print ", ") |
(print ", ") |
||
(recur (inc n))))) |
(recur (inc n))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
<syntaxhighlight lang="cobol"> |
|||
<lang cobol> IDENTIFICATION DIVISION. |
|||
IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. Loop-N-And-Half. |
PROGRAM-ID. Loop-N-And-Half. |
||
Line 416: | Line 1,246: | ||
GOBACK |
GOBACK |
||
. |
. |
||
</syntaxhighlight> |
|||
Free-form, 'List'-free version, using DISPLAY NO ADVANCING. |
Free-form, 'List'-free version, using DISPLAY NO ADVANCING. |
||
<lang |
<syntaxhighlight lang="cobol"> |
||
IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. LOOP-1p5-NOADV. |
PROGRAM-ID. LOOP-1p5-NOADV. |
||
DATA DIVISION. |
DATA DIVISION. |
||
Line 435: | Line 1,267: | ||
END-PERFORM. |
END-PERFORM. |
||
STOP RUN. |
STOP RUN. |
||
END-PROGRAM. |
END-PROGRAM. |
||
</syntaxhighlight> |
|||
Free-form, GO TO, 88-level. Paragraphs in PROCEDURE DIVISION. |
Free-form, GO TO, 88-level. Paragraphs in PROCEDURE DIVISION. |
||
<lang |
<syntaxhighlight lang="cobol"> |
||
IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. LOOP-1p5-NOADV-GOTO. |
PROGRAM-ID. LOOP-1p5-NOADV-GOTO. |
||
DATA DIVISION. |
DATA DIVISION. |
||
Line 454: | Line 1,288: | ||
02-DONE. |
02-DONE. |
||
STOP RUN. |
STOP RUN. |
||
END-PROGRAM. |
END-PROGRAM. |
||
</syntaxhighlight> |
|||
Using 'PERFORM VARYING' |
Using 'PERFORM VARYING' |
||
<lang |
<syntaxhighlight lang="cobol"> |
||
IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. LOOP-1p5-NOADV-VARY. |
PROGRAM-ID. LOOP-1p5-NOADV-VARY. |
||
DATA DIVISION. |
DATA DIVISION. |
||
Line 472: | Line 1,308: | ||
END-PERFORM. |
END-PERFORM. |
||
STOP RUN. |
STOP RUN. |
||
END-PROGRAM. |
END-PROGRAM. |
||
</syntaxhighlight> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
# Loop plus half. This code shows how to break out of a loop early |
# Loop plus half. This code shows how to break out of a loop early |
||
# on the last iteration. For the contrived example, there are better |
# on the last iteration. For the contrived example, there are better |
||
Line 489: | Line 1,326: | ||
s += ', ' |
s += ', ' |
||
console.log s |
console.log s |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
With tags: |
With tags: |
||
<syntaxhighlight lang="cfm"> |
|||
<lang cfm><cfloop index = "i" from = "1" to = "10"> |
|||
<cfloop index = "i" from = "1" to = "10"> |
|||
#i# |
#i# |
||
<cfif i EQ 10> |
<cfif i EQ 10> |
||
Line 499: | Line 1,337: | ||
</cfif> |
</cfif> |
||
, |
, |
||
</cfloop |
</cfloop> |
||
</syntaxhighlight> |
|||
With script: |
With script: |
||
<syntaxhighlight lang="cfm"> |
|||
<lang cfm><cfscript> |
|||
<cfscript> |
|||
for( i = 1; i <= 10; i++ ) //note: the ++ notation works only on version 8 up, otherwise use i=i+1 |
for( i = 1; i <= 10; i++ ) //note: the ++ notation works only on version 8 up, otherwise use i=i+1 |
||
{ |
{ |
||
Line 513: | Line 1,353: | ||
writeOutput( ", " ); |
writeOutput( ", " ); |
||
} |
} |
||
</cfscript |
</cfscript> |
||
</syntaxhighlight> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(loop for i from 1 below 10 do |
(loop for i from 1 below 10 do |
||
(princ i) (princ ", ") |
(princ i) (princ ", ") |
||
finally (princ i)) |
finally (princ i)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
or |
or |
||
<syntaxhighlight lang="lisp"> |
|||
<lang lisp>(loop for i from 1 upto 10 do |
|||
(loop for i from 1 upto 10 do |
|||
(princ i) |
(princ i) |
||
(if (= i 10) (return)) |
(if (= i 10) (return)) |
||
(princ ", ")) |
(princ ", ")) |
||
</syntaxhighlight> |
|||
but for such simple tasks we can use format's powers: |
but for such simple tasks we can use format's powers: |
||
< |
<syntaxhighlight lang="lisp"> |
||
(format t "~{~a~^, ~}" (loop for i from 1 to 10 collect i)) |
(format t "~{~a~^, ~}" (loop for i from 1 to 10 collect i)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== Using DO === |
|||
<syntaxhighlight lang="lisp"> |
|||
(do ((i 1 (incf i))) ; Initialize to 1 and increment on every loop |
|||
((> i 10)) ; Break condition |
|||
(princ i) ; Print the iteration number |
|||
(when (= i 10) (go end)) ; Use the implicit tagbody and go to end tag when reach the last iteration |
|||
(princ ", ") ; Printing the comma is jumped by the go statement |
|||
end) ; The tag |
|||
</syntaxhighlight> |
|||
or |
|||
<syntaxhighlight lang="lisp"> |
|||
(do ; Not exactly separate statements for the number and the comma |
|||
((i 1 (incf i))) ; Initialize to 1 and increment on every loop |
|||
((> i 9) (princ i)) ; Break condition when iteration is the last number, print it |
|||
(princ i) ; Print number statement |
|||
(princ ", ")) ; Print comma statement |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|Cowgol}}== |
|||
<syntaxhighlight lang="cowgol"> |
|||
include "cowgol.coh"; |
|||
var i: uint8 := 1; |
|||
loop |
|||
print_i8(i); |
|||
if i == 10 then break; end if; |
|||
print(", "); |
|||
i := i + 1; |
|||
end loop; |
|||
print_nl(); |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
===Iterative=== |
===Iterative=== |
||
<syntaxhighlight lang="d"> |
|||
<lang d>import std.stdio; |
|||
import std.stdio; |
|||
void main() { |
void main() { |
||
Line 548: | Line 1,433: | ||
writeln(); |
writeln(); |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
||
===Functional Style=== |
===Functional Style=== |
||
<syntaxhighlight lang="d"> |
|||
<lang d>void main() { |
|||
void main() { |
|||
import std.stdio, std.range, std.algorithm, std.conv, std.string; |
import std.stdio, std.range, std.algorithm, std.conv, std.string; |
||
iota(1, 11).map!text.join(", ").writeln; |
iota(1, 11).map!text.join(", ").writeln; |
||
Line 558: | Line 1,445: | ||
// A simpler solution: |
// A simpler solution: |
||
writefln("%(%d, %)", iota(1, 11)); |
writefln("%(%d, %)", iota(1, 11)); |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
Line 564: | Line 1,452: | ||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
<syntaxhighlight lang="dart"> |
|||
<lang Dart>String loopPlusHalf(start, end) { |
|||
String loopPlusHalf(start, end) { |
|||
var result = ''; |
var result = ''; |
||
for(int i = start; i <= end; i++) { |
for(int i = start; i <= end; i++) { |
||
Line 578: | Line 1,467: | ||
void main() { |
void main() { |
||
print(loopPlusHalf(1, 10)); |
print(loopPlusHalf(1, 10)); |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi>program LoopsNPlusOneHalf; |
|||
program LoopsNPlusOneHalf; |
|||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 598: | Line 1,489: | ||
end; |
end; |
||
Writeln; |
Writeln; |
||
end. |
end. |
||
</syntaxhighlight> |
|||
=={{header|Draco}}== |
|||
<syntaxhighlight lang="draco"> |
|||
proc nonrec main() void: |
|||
byte i; |
|||
i := 1; |
|||
while |
|||
write(i); |
|||
i := i + 1; |
|||
i <= 10 |
|||
do |
|||
write(", ") |
|||
od |
|||
corp |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi>var i : Integer; |
|||
var i : Integer; |
|||
for i := 1 to 10 do begin |
for i := 1 to 10 do begin |
||
Line 608: | Line 1,517: | ||
if i < 10 then |
if i < 10 then |
||
Print(', '); |
Print(', '); |
||
end; |
end; |
||
</syntaxhighlight> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
A typical loop+break solution: |
A typical loop+break solution: |
||
<syntaxhighlight lang="e"> |
|||
<lang e>var i := 1 |
|||
var i := 1 |
|||
while (true) { |
while (true) { |
||
print(i) |
print(i) |
||
Line 619: | Line 1,530: | ||
print(", ") |
print(", ") |
||
i += 1 |
i += 1 |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
Using the loop primitive in a semi-functional style: |
Using the loop primitive in a semi-functional style: |
||
<syntaxhighlight lang="e"> |
|||
<lang e>var i := 1 |
|||
var i := 1 |
|||
__loop(fn { |
__loop(fn { |
||
print(i) |
print(i) |
||
Line 633: | Line 1,546: | ||
true |
true |
||
} |
} |
||
}) |
}) |
||
</syntaxhighlight> |
|||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang="easylang"> |
|||
for i = 1 to 10 |
|||
write i |
|||
if i < 10 |
|||
write ", " |
|||
. |
|||
. |
|||
</syntaxhighlight> |
|||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(string-delimiter "") |
(string-delimiter "") |
||
Line 646: | Line 1,570: | ||
(string-join (range 1 11) ",") |
(string-join (range 1 11) ",") |
||
→ 1,2,3,4,5,6,7,8,9,10 |
→ 1,2,3,4,5,6,7,8,9,10 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EDSAC order code}}== |
=={{header|EDSAC order code}}== |
||
<syntaxhighlight lang="edsac"> |
|||
<lang edsac>[ N and a half times loop |
|||
[ N and a half times loop |
|||
======================= |
======================= |
||
Line 689: | Line 1,614: | ||
[ 25 ] PF |
[ 25 ] PF |
||
EZPF |
EZPF |
||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
||
===Alternative=== |
|||
In the original EDSAC solution, the last number is printed outside the loop. My understanding of the task is that all numbers should be printed inside the loop, and control should then pass out of the loop without printing a comma after the last number. |
|||
To avoid dragging in a number-printing subroutine just to print 10, the output from the subroutines below has been changed to the single digits 0..9. |
|||
The first subroutine sticks to the task description: "in the last iteration, execute only part of the loop body". Two conditional jumps are encountered each time round the loop. The second subroutine skips the first part of the first iteration. This may not exactly fit the task description, but it has the advantage of requiring only one conditional jump within the loop. Cf. the S-lang solution and the comment by its author. |
|||
<syntaxhighlight lang="edsac"> |
|||
[Loop-and-a-half for Rosetta Code. |
|||
EDSAC program, Initial Orders 2.] |
|||
T64K [load at location 64 (arbitrary choice)] |
|||
GK [set @ (theta) parameter] |
|||
[Constants] |
|||
[0] OF [digit 9] |
|||
[1] JF [to inc digit after subtracting 9] |
|||
[2] #F [figures mode] |
|||
[3] !F [space] |
|||
[4] NF [comma (in figures mode)] |
|||
[5] @F [carriage return] |
|||
[6] &F [line feed] |
|||
[Variable] |
|||
[7] PF [current digit] |
|||
[First subroutine to print digits 0..9] |
|||
[8] A3F T20@ [plant return link as usual] |
|||
T7@ [digit := 0] |
|||
[11] O7@ [loop: print digit] |
|||
A7@ S@ [is digit 9?] |
|||
E20@ [if so, jump to exit] |
|||
O4@ O3@ [print comma and space] |
|||
A1@ [inc digit in acc] |
|||
T7@ [update digit in store] |
|||
E11@ [always loop back] |
|||
[20] ZF [(planted) return to caller with acc = 0] |
|||
[Second subroutine to print digits 0..9 |
|||
Instead of saying "print a comma after each digit except the last" |
|||
it says "print a comma before each digit except the first".] |
|||
[21] A3F T33@ [plant return link as usual] |
|||
T7@ [digit := 0] |
|||
E29@ [jump into middle of loop] |
|||
[25] A1@ [loop: inc digit in acc] |
|||
T7@ [update digit in store] |
|||
O4@ O3@ [print comma and space] |
|||
[29] O7@ [print digit] |
|||
A7@ S@ [is digit 9?] |
|||
G25@ [if not, loop back] |
|||
[33] ZF [(planted) return to caller with acc = 0] |
|||
[Enter with acc = 0] |
|||
[34] O2@ [set teleprinter to figures] |
|||
A35@ G8@ [call first subroutine] |
|||
O5@ O6@ [print CR, LF] |
|||
A39@ G21@ [call second subroutine] |
|||
O5@ O6@ [print CR, LF] |
|||
O2@ [print dummy character to flush teleprinter buffer] |
|||
ZF [stop] |
|||
E34Z [define entry point] |
|||
PF [value of acc on entry (here = 0)] |
|||
[end] |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 |
|||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 |
|||
</pre> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
<lang |
<syntaxhighlight lang="elixir"> |
||
defmodule Loops do |
|||
def n_plus_one_half([]), do: IO.puts "" |
def n_plus_one_half([]), do: IO.puts "" |
||
def n_plus_one_half([x]), do: IO.puts x |
def n_plus_one_half([x]), do: IO.puts x |
||
Line 703: | Line 1,696: | ||
end |
end |
||
Enum.to_list(1..10) |> Loops.n_plus_one_half |
Enum.to_list(1..10) |> Loops.n_plus_one_half |
||
</syntaxhighlight> |
|||
=={{header|EMal}}== |
|||
<syntaxhighlight lang="emal"> |
|||
int LAST_ITERATION = 10 |
|||
for int i = 1; i <= LAST_ITERATION ; ++i |
|||
write(i) |
|||
if i == LAST_ITERATION do break end |
|||
write(", ") |
|||
end |
|||
writeLine() |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
<syntaxhighlight lang="erlang"> |
|||
<lang erlang>%% Implemented by Arjun Sunel |
|||
%% Implemented by Arjun Sunel |
|||
-module(loop). |
-module(loop). |
||
-export([main/0]). |
-export([main/0]). |
||
Line 720: | Line 1,730: | ||
io:format("~p\n",[N]) |
io:format("~p\n",[N]) |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
FOR I=1 TO 10 DO |
FOR I=1 TO 10 DO |
||
PRINT(I;) |
PRINT(I;) |
||
Line 730: | Line 1,739: | ||
PRINT(", ";) |
PRINT(", ";) |
||
END FOR |
END FOR |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
<syntaxhighlight lang="euphoria"> |
|||
<lang Euphoria> |
|||
for i = 1 to 10 do |
for i = 1 to 10 do |
||
printf(1, "%g", {i}) |
printf(1, "%g", {i}) |
||
Line 742: | Line 1,749: | ||
end if |
end if |
||
end for |
end for |
||
</syntaxhighlight> |
|||
</lang> |
|||
While, yes, use of <code>exit</code> would also work here, it is slightly faster to code it this way, if only the last iteration has something different. |
While, yes, use of <code>exit</code> would also work here, it is slightly faster to code it this way, if only the last iteration has something different. |
||
Line 748: | Line 1,755: | ||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
Functional version that works for lists of any length |
Functional version that works for lists of any length |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let rec print (lst : int list) = |
let rec print (lst : int list) = |
||
match lst with |
match lst with |
||
Line 759: | Line 1,766: | ||
print [1..10] |
print [1..10] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
<lang |
<syntaxhighlight lang="factor"> |
||
: print-comma-list ( n -- ) |
|||
[ [1,b] ] keep '[ |
[ [1,b] ] keep '[ |
||
[ number>string write ] |
[ number>string write ] |
||
[ _ = [ ", " write ] unless ] bi |
[ _ = [ ", " write ] unless ] bi |
||
] each nl ; |
] each nl ; |
||
</syntaxhighlight> |
|||
=={{header|Falcon}}== |
=={{header|Falcon}}== |
||
<lang |
<syntaxhighlight lang="falcon"> |
||
for value = 1 to 10 |
|||
formiddle |
formiddle |
||
>> value |
>> value |
||
Line 775: | Line 1,785: | ||
end |
end |
||
forlast: > value |
forlast: > value |
||
end |
end |
||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
Line 782: | Line 1,793: | ||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
<lang |
<syntaxhighlight lang="false"> |
||
1[$9>~][$.", "1+]#. |
|||
</syntaxhighlight> |
|||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 800: | Line 1,813: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FBSL}}== |
|||
<lang qbasic> |
|||
#APPTYPE CONSOLE |
|||
For Dim i = 1 To 10 |
|||
PRINT i; |
|||
IF i < 10 THEN PRINT ", "; |
|||
Next |
|||
PAUSE</lang> |
|||
Output |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
Press any key to continue...</pre> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
<lang |
<syntaxhighlight lang="forth"> |
||
: comma-list ( n -- ) |
|||
dup 1 ?do i 1 .r ." , " loop |
dup 1 ?do i 1 .r ." , " loop |
||
. ; |
. ; |
||
</syntaxhighlight> |
|||
<lang |
<syntaxhighlight lang="forth"> |
||
: comma-list ( n -- ) |
|||
dup 1+ 1 do |
dup 1+ 1 do |
||
i 1 .r |
i 1 .r |
||
dup i = if leave then \ or DROP UNLOOP EXIT to exit loop and the function |
dup i = if leave then \ or DROP UNLOOP EXIT to exit loop and the function |
||
[char] , emit space |
[char] , emit space |
||
loop drop ; |
loop drop ; |
||
</syntaxhighlight> |
|||
<lang |
<syntaxhighlight lang="forth"> |
||
: comma-list ( n -- ) |
|||
1 |
1 |
||
begin dup 1 .r |
begin dup 1 .r |
||
2dup <> |
2dup <> |
||
while ." , " 1+ |
while ." , " 1+ |
||
repeat 2drop ; |
repeat 2drop ; |
||
</syntaxhighlight> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|FORTRAN|IV and later}} |
{{works with|FORTRAN|IV and later}} |
||
<syntaxhighlight lang="fortran"> |
|||
<lang fortran>C Loops N plus one half - Fortran IV (1964) |
|||
C Loops N plus one half - Fortran IV (1964) |
|||
INTEGER I |
INTEGER I |
||
WRITE(6,301) (I,I=1,10) |
WRITE(6,301) (I,I=1,10) |
||
301 FORMAT((I3,',')) |
301 FORMAT((I3,',')) |
||
END |
END |
||
</syntaxhighlight> |
|||
{{works with|Fortran|77 and later}} |
{{works with|Fortran|77 and later}} |
||
<syntaxhighlight lang="fortran"> |
|||
<lang fortran>C WARNING: This program is not valid ANSI FORTRAN 77 code. It uses |
|||
C WARNING: This program is not valid ANSI FORTRAN 77 code. It uses |
|||
C two nonstandard characters on the lines labelled 5001 and 5002. |
C two nonstandard characters on the lines labelled 5001 and 5002. |
||
C Many F77 compilers should be okay with it, but it is *not* |
C Many F77 compilers should be okay with it, but it is *not* |
||
Line 891: | Line 1,901: | ||
C5001 FORMAT (T3, ADVANCE='NO') |
C5001 FORMAT (T3, ADVANCE='NO') |
||
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}} |
||
<lang |
<syntaxhighlight lang="fortran"> |
||
i = 1 |
|||
do |
do |
||
write(*, '(I0)', advance='no') i |
write(*, '(I0)', advance='no') i |
||
Line 902: | Line 1,914: | ||
i = i + 1 |
i = i + 1 |
||
end do |
end do |
||
write(*,*) |
write(*,*) |
||
</syntaxhighlight> |
|||
=={{header|FreeBASIC}}== |
|||
<lang freebasic>' FB 1.05.0 Win64 |
|||
For i As Integer = 1 To 10 |
|||
Print Str(i); |
|||
If i < 10 Then Print ", "; |
|||
Next |
|||
Print |
|||
Sleep</lang> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|FutureBasic}}== |
|||
<lang futurebasic> |
|||
include "ConsoleWindow" |
|||
dim as long i, num : num = 10 |
|||
for i = 1 to num |
|||
print i; |
|||
if i = num then exit for |
|||
print ","; |
|||
next i |
|||
</lang> |
|||
Output: |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|Gambas}}== |
|||
'''[https://gambas-playground.proko.eu/?gist=c43cc581e5f93e70c5dc82733f609a7e Click this link to run this code]''' |
|||
<lang gambas>Public Sub Main() |
|||
Dim siLoop As Short |
|||
For siLoop = 1 To 10 |
|||
Print siLoop; |
|||
If siLoop <> 10 Then Print ", "; |
|||
Next |
|||
End</lang> |
|||
Output: |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
<lang |
<syntaxhighlight lang="gap"> |
||
n := 10; |
|||
for i in [1 .. n] do |
for i in [1 .. n] do |
||
Print(i); |
Print(i); |
||
Line 962: | Line 1,927: | ||
Print("\n"); |
Print("\n"); |
||
fi; |
fi; |
||
od; |
od; |
||
</syntaxhighlight> |
|||
=={{header|GML}}== |
=={{header|GML}}== |
||
<lang |
<syntaxhighlight lang="gml"> |
||
str = "" |
|||
for(i = 1; i <= 10; i += 1) |
for(i = 1; i <= 10; i += 1) |
||
{ |
{ |
||
Line 972: | Line 1,939: | ||
str += ", " |
str += ", " |
||
} |
} |
||
show_message(str) |
show_message(str) |
||
</syntaxhighlight> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
<lang |
<syntaxhighlight lang="go"> |
||
package main |
|||
import "fmt" |
import "fmt" |
||
Line 988: | Line 1,957: | ||
fmt.Print(", ") |
fmt.Print(", ") |
||
} |
} |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Gosu}}== |
=={{header|Gosu}}== |
||
<lang |
<syntaxhighlight lang="java"> |
||
var out = System.out |
|||
for(i in 1..10) { |
for(i in 1..10) { |
||
if(i > 1) out.print(", ") |
if(i > 1) out.print(", ") |
||
out.print(i) |
out.print(i) |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
<lang |
<syntaxhighlight lang="groovy"> |
||
for(i in (1..10)) { |
|||
print i |
print i |
||
if (i == 10) break |
if (i == 10) break |
||
print ', ' |
print ', ' |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
Output: |
Output: |
||
Line 1,009: | Line 1,983: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
<lang |
<syntaxhighlight lang="haskell"> |
||
main :: IO () |
|||
main = forM_ [1 .. 10] $ \n -> do |
main = forM_ [1 .. 10] $ \n -> do |
||
putStr $ show n |
putStr $ show n |
||
putStr $ if n == 10 then "\n" else ", " |
putStr $ if n == 10 then "\n" else ", " |
||
</syntaxhighlight> |
|||
You can also use intersperse :: a -> [a] -> [a] |
You can also use intersperse :: a -> [a] -> [a] |
||
<syntaxhighlight lang="haskell"> |
|||
<lang haskell>intercalate ", " (map show [1..10])</lang> |
|||
intercalate ", " (map show [1..10]) |
|||
</syntaxhighlight> |
|||
=={{header|Haxe}}== |
|||
<syntaxhighlight lang="haxe"> |
|||
for (i in 1...11) |
|||
Sys.print('$i${i == 10 ? '\n' : ', '}'); |
|||
</syntaxhighlight> |
|||
=={{header|hexiscript}}== |
|||
<syntaxhighlight lang="hexiscript"> |
|||
for let i 1; i <= 10; i++ |
|||
print i |
|||
if i = 10; break; endif |
|||
print ", " |
|||
endfor |
|||
println "" |
|||
</syntaxhighlight> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
<lang |
<syntaxhighlight lang="hicest"> |
||
DO i = 1, 10 |
|||
WRITE(APPend) i |
WRITE(APPend) i |
||
IF(i < 10) WRITE(APPend) ", " |
IF(i < 10) WRITE(APPend) ", " |
||
ENDDO |
ENDDO |
||
</syntaxhighlight> |
|||
=={{header|HolyC}}== |
=={{header|HolyC}}== |
||
<lang |
<syntaxhighlight lang="holyc"> |
||
U8 i, max = 10; |
|||
for (i = 1; i <= max; i++) { |
for (i = 1; i <= max; i++) { |
||
Print("%d", i); |
Print("%d", i); |
||
Line 1,030: | Line 2,027: | ||
Print(", "); |
Print(", "); |
||
} |
} |
||
Print("\n"); |
Print("\n"); |
||
</syntaxhighlight> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
|||
<syntaxhighlight lang="icon"> |
|||
procedure main() |
|||
every writes(i := 1 to 10) do |
|||
if i = 10 then break write() |
|||
else writes(", ") |
|||
end |
|||
</syntaxhighlight> |
|||
The above can be written more succinctly as: |
|||
<syntaxhighlight lang="icon"> |
|||
every writes(c := "",1 to 10) do c := "," |
|||
</syntaxhighlight> |
|||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
Line 1,036: | Line 2,048: | ||
Nobody would ever use a loop in IDL to output a vector of numbers - the requisite output would be generated something like this: |
Nobody would ever use a loop in IDL to output a vector of numbers - the requisite output would be generated something like this: |
||
<syntaxhighlight lang="idl"> |
|||
<lang idl>print,indgen(10)+1,format='(10(i,:,","))'</lang> |
|||
print,indgen(10)+1,format='(10(i,:,","))' |
|||
</syntaxhighlight> |
|||
However if a loop had to be used it could be done like this: |
However if a loop had to be used it could be done like this: |
||
<syntaxhighlight lang="idl"> |
|||
<lang idl>for i=1,10 do begin |
|||
for i=1,10 do begin |
|||
print,i,format='($,i)' |
print,i,format='($,i)' |
||
if i lt 10 then print,",",format='($,a)' |
if i lt 10 then print,",",format='($,a)' |
||
endfor |
endfor |
||
</syntaxhighlight> |
|||
(which merely suppresses the printing of the comma in the last iteration); |
(which merely suppresses the printing of the comma in the last iteration); |
||
Line 1,049: | Line 2,065: | ||
or like this: |
or like this: |
||
<syntaxhighlight lang="idl"> |
|||
<lang idl>for i=1,10 do begin |
|||
for i=1,10 do begin |
|||
print,i,format='($,i)' |
print,i,format='($,i)' |
||
if i eq 10 then break |
if i eq 10 then break |
||
print,",",format='($,a)' |
print,",",format='($,a)' |
||
end |
end |
||
</syntaxhighlight> |
|||
(which terminates the loop early if the last element is reached). |
(which terminates the loop early if the last element is reached). |
||
=={{header|Icon}} and {{header|Unicon}}== |
|||
<lang Icon>procedure main() |
|||
every writes(i := 1 to 10) do |
|||
if i = 10 then break write() |
|||
else writes(", ") |
|||
end</lang> |
|||
The above can be written more succinctly as: |
|||
<lang Icon>every writes(c := "",1 to 10) do c := "," |
|||
</lang> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
<syntaxhighlight lang="j"> |
|||
<lang j>output=: verb define |
|||
output=: verb define |
|||
buffer=: buffer,y |
buffer=: buffer,y |
||
) |
) |
||
Line 1,081: | Line 2,089: | ||
end. |
end. |
||
end. |
end. |
||
echo buffer |
|||
) |
|||
)</lang> |
|||
</syntaxhighlight> |
|||
Example use: |
Example use: |
||
<syntaxhighlight lang="j"> |
|||
<lang j> loopy 0 |
|||
loopy 0 |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10</lang> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</syntaxhighlight> |
|||
That said, note that neither loops nor output statements are necessary: |
That said, note that neither loops nor output statements are necessary: |
||
<syntaxhighlight lang="j"> |
|||
<lang j> ;}.,(', ' ; ":)&> 1+i.10 |
|||
;}.,(', ' ; ":)&> 1+i.10 |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</syntaxhighlight> |
|||
And, note also that this sort of data driven approach can also deal with more complex issues: |
And, note also that this sort of data driven approach can also deal with more complex issues: |
||
<syntaxhighlight lang="j"> |
|||
<lang j> commaAnd=: ":&.> ;@,. -@# {. (<;._1 '/ and /') ,~ (<', ') #~ # |
|||
commaAnd=: ":&.> ;@,. -@# {. (<;._1 '/ and /') ,~ (<', ') #~ # |
|||
commaAnd i.5 |
commaAnd i.5 |
||
0, 1, 2, 3 and 4 |
0, 1, 2, 3 and 4 |
||
</syntaxhighlight> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
<syntaxhighlight lang="java"> |
|||
<lang java>public static void main(String[] args) { |
|||
public static void main(String[] args) { |
|||
for (int i = 1; ; i++) { |
for (int i = 1; ; i++) { |
||
System.out.print(i); |
System.out.print(i); |
||
Line 1,108: | Line 2,124: | ||
} |
} |
||
System.out.println(); |
System.out.println(); |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
<lang |
<syntaxhighlight lang="javascript"> |
||
function loop_plus_half(start, end) { |
|||
var str = '', |
var str = '', |
||
i; |
i; |
||
Line 1,124: | Line 2,142: | ||
} |
} |
||
alert(loop_plus_half(1, 10)); |
alert(loop_plus_half(1, 10)); |
||
</syntaxhighlight> |
|||
Alternatively, if we stand back for a moment from imperative assumptions about the nature and structure of computing tasks, it becomes clear that the problem of special transitional cases as a pattern terminates has no necessary connection with loops. (See the comments accompanying the ACL2, Haskell, IDL, J and R examples above and below, and see also some of the approaches taken in languages like Clojure and Scala. |
Alternatively, if we stand back for a moment from imperative assumptions about the nature and structure of computing tasks, it becomes clear that the problem of special transitional cases as a pattern terminates has no necessary connection with loops. (See the comments accompanying the ACL2, Haskell, IDL, J and R examples above and below, and see also some of the approaches taken in languages like Clojure and Scala. |
||
Line 1,130: | Line 2,149: | ||
If a JavaScript expression evaluates to an array [1 .. 10] of integers, for example, we can map that array directly to a comma-delimited string by using the '''Array.join()''' function, writing something like: |
If a JavaScript expression evaluates to an array [1 .. 10] of integers, for example, we can map that array directly to a comma-delimited string by using the '''Array.join()''' function, writing something like: |
||
<syntaxhighlight lang="javascript"> |
|||
<lang JavaScript>function range(m, n) { |
|||
function range(m, n) { |
|||
return Array.apply(null, Array(n - m + 1)).map( |
return Array.apply(null, Array(n - m + 1)).map( |
||
function (x, i) { |
function (x, i) { |
||
Line 1,140: | Line 2,160: | ||
console.log( |
console.log( |
||
range(1, 10).join(', ') |
range(1, 10).join(', ') |
||
); |
); |
||
</syntaxhighlight> |
|||
Output: |
Output: |
||
<syntaxhighlight lang="javascript"> |
|||
<lang JavaScript>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</lang> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</syntaxhighlight> |
|||
Otherwise, any special transitional case at the end of a pattern can be handled by defining conditional values for one or more sub-expressions: |
Otherwise, any special transitional case at the end of a pattern can be handled by defining conditional values for one or more sub-expressions: |
||
<syntaxhighlight lang="javascript"> |
|||
<lang JavaScript>function range(m, n) { |
|||
function range(m, n) { |
|||
return Array.apply(null, Array(n - m + 1)).map(function (x, i) { |
return Array.apply(null, Array(n - m + 1)).map(function (x, i) { |
||
return m + i; |
return m + i; |
||
Line 1,167: | Line 2,191: | ||
) |
) |
||
})(1, 10) |
})(1, 10) |
||
); |
); |
||
</syntaxhighlight> |
|||
Output: |
Output: |
||
<syntaxhighlight lang="javascript"> |
|||
<lang JavaScript>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</lang> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</syntaxhighlight> |
|||
==== Otherwise ==== |
==== Otherwise ==== |
||
<syntaxhighlight lang="javascript"> |
|||
<lang JavaScript>var s=1, e=10 |
|||
var s=1, e=10 |
|||
for (var i=s; i<=e; i+=1) { |
for (var i=s; i<=e; i+=1) { |
||
document.write( i==s ? '' : ', ', i ) |
document.write( i==s ? '' : ', ', i ) |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
or |
or |
||
<syntaxhighlight lang="javascript"> |
|||
<lang JavaScript>var s=1, e=10 |
|||
var s=1, e=10 |
|||
for (;; s+=1) { |
for (;; s+=1) { |
||
document.write( s ) |
document.write( s ) |
||
if (s==e) break |
if (s==e) break |
||
document.write( ', ' ) |
document.write( ', ' ) |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,190: | Line 2,221: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
In jq, it is idiomatic to view a range of integers with boundaries m and n as [m, n), i.e. including m but excluding n. |
In jq, it is idiomatic to view a range of integers with boundaries m and n as [m, n), i.e. including m but excluding n. |
||
<syntaxhighlight lang="jq"> |
|||
<lang jq>One approach is to construct the answer incrementally: |
|||
One approach is to construct the answer incrementally: |
|||
def loop_plus_half(m;n): |
def loop_plus_half(m;n): |
||
if m<n then reduce range(m+1;n) as $i (m|tostring; . + ", " + ($i|tostring)) |
if m<n then reduce range(m+1;n) as $i (m|tostring; . + ", " + ($i|tostring)) |
||
Line 1,198: | Line 2,230: | ||
# An alternative that is shorter and perhaps closer to the task description because it uses range(m;n) is as follows: |
# An alternative that is shorter and perhaps closer to the task description because it uses range(m;n) is as follows: |
||
def loop_plus_half2(m;n): |
def loop_plus_half2(m;n): |
||
[range(m;n) | if . == m then . else ", ", . end | tostring] | join(""); |
[range(m;n) | if . == m then . else ", ", . end | tostring] | join(""); |
||
</syntaxhighlight> |
|||
{{Out}} |
{{Out}} |
||
loop_plus_half2(1;11) |
loop_plus_half2(1;11) |
||
Line 1,205: | Line 2,238: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
The short-circuiting && is idiomatic to Julia - the second expression will only be evaluated if the first one is true. |
The short-circuiting && is idiomatic to Julia - the second expression will only be evaluated if the first one is true. |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
for i = 1:10 |
for i = 1:10 |
||
print(i) |
print(i) |
||
Line 1,211: | Line 2,244: | ||
print(", ") |
print(", ") |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lasso}}== |
|||
<lang Lasso>local(out) = '' |
|||
loop(10) => { |
|||
#out->append(loop_count) |
|||
loop_count == 10 ? loop_abort |
|||
#out->append(', ') |
|||
} |
|||
#out</lang> |
|||
=={{header|K}}== |
=={{header|K}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang K> p:{`0:$x} / output |
|||
p:{`0:$x} / output |
|||
i:1;do[10;p[i];p[:[i<10;", "]];i+:1];p@"\n" |
i:1;do[10;p[i];p[:[i<10;", "]];i+:1];p@"\n" |
||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
</syntaxhighlight> |
|||
Alternative solutions: |
Alternative solutions: |
||
<syntaxhighlight lang="k"> |
|||
<lang K> 10 {p@x;p@:[x<10;", ";"\n"];x+1}\1; |
|||
{p@x;p@:[x<10;", ";"\n"];x+1} |
10 {p@x;p@:[x<10;", ";"\n"];x+1}\1; |
||
{p@x;p@:[x<10;", ";"\n"];x+1}'1+!10; /variant |
|||
</syntaxhighlight> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
<lang |
<syntaxhighlight lang="scala"> |
||
// version 1.0.6 |
|||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 1,243: | Line 2,272: | ||
if (i < 10) print(", ") |
if (i < 10) print(", ") |
||
} |
} |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
Line 1,252: | Line 2,282: | ||
=={{header|LabVIEW}}== |
=={{header|LabVIEW}}== |
||
{{VI snippet}}<br/>[[File:LabVIEW_Loops_N_plus_one_half.png]] |
{{VI snippet}}<br/>[[File:LabVIEW_Loops_N_plus_one_half.png]] |
||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
{def loops_N_plus_one_half |
|||
{lambda {:i :n} |
|||
{if {> :i :n} |
|||
then (end of loop with a dot) |
|||
else {if {= :i 6} then {br}:i else :i}{if {= :i :n} then . else ,} |
|||
{loops_N_plus_one_half {+ :i 1} :n}}}} |
|||
-> loops_N_plus_one_half |
|||
{loops_N_plus_one_half 0 10} |
|||
-> 0, 1, 2, 3, 4, 5, |
|||
6, 7, 8, 9, 10. (end of loop with a dot) |
|||
</syntaxhighlight> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
# Loop |
|||
$i = 1 |
|||
loop { |
|||
fn.print($i) |
|||
if($i === 10) { |
|||
con.break |
|||
} |
|||
fn.print(\,\s) |
|||
$i += 1 |
|||
} |
|||
fn.println() |
|||
# Array generate from and join |
|||
fn.println(fn.join(\,\s, fn.arrayGenerateFrom(fn.inc, 10))) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
<syntaxhighlight lang="lang5"> |
|||
<lang lang5>: , dup ", " 2 compress "" join ; |
|||
: , dup ", " 2 compress "" join ; |
|||
1 do dup 10 != if dup , . 1 + else . break then loop |
|||
</syntaxhighlight> |
|||
Word: [[Loops/For#Lang5]] |
Word: [[Loops/For#Lang5]] |
||
<syntaxhighlight lang="lang5"> |
|||
<lang lang5>: 2string 2 compress "" join ; |
|||
: 2string 2 compress "" join ; |
|||
: , dup 10 != if ", " 2string then ; |
: , dup 10 != if ", " 2string then ; |
||
1 10 "dup , . 1+" times |
1 10 "dup , . 1+" times |
||
</syntaxhighlight> |
|||
=={{header|Lasso}}== |
|||
<syntaxhighlight lang="lasso"> |
|||
local(out) = '' |
|||
loop(10) => { |
|||
#out->append(loop_count) |
|||
loop_count == 10 ? loop_abort |
|||
#out->append(', ') |
|||
} |
|||
#out |
|||
</syntaxhighlight> |
|||
=={{header|Lhogho}}== |
=={{header|Lhogho}}== |
||
<code>type</code> doesn't output a newline. The <code>print</code> outputs one. |
<code>type</code> doesn't output a newline. The <code>print</code> outputs one. |
||
<lang |
<syntaxhighlight lang="logo"> |
||
for "i [1 10] |
|||
[ |
[ |
||
type :i |
type :i |
||
Line 1,271: | Line 2,358: | ||
] |
] |
||
] |
] |
||
print |
print |
||
</syntaxhighlight> |
|||
A more list-y way of doing it |
A more list-y way of doing it |
||
<lang |
<syntaxhighlight lang="logo"> |
||
to join :lst :sep |
|||
if list? :lst |
if list? :lst |
||
[ |
[ |
||
Line 1,290: | Line 2,379: | ||
make "aList [1 2 3 4 5 6 7 8 9 10] |
make "aList [1 2 3 4 5 6 7 8 9 10] |
||
print join :aList "|, | |
print join :aList "|, | |
||
</syntaxhighlight> |
|||
=={{header|Liberty BASIC}}== |
|||
Keyword 'exit' allows the termination. |
|||
<lang lb> |
|||
for i =1 to 10 |
|||
print i; |
|||
if i =10 then exit for |
|||
print ", "; |
|||
next i |
|||
end |
|||
</lang> |
|||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
<syntaxhighlight lang="lisaac"> |
|||
<lang Lisaac>Section Header |
|||
Section Header |
|||
+ name := LOOP_AND_HALF; |
+ name := LOOP_AND_HALF; |
||
Line 1,322: | Line 2,402: | ||
}; |
}; |
||
'\n'.print; |
'\n'.print; |
||
); |
); |
||
</syntaxhighlight> |
|||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
<syntaxhighlight lang="livecode"> |
|||
<lang LiveCode>repeat with n = 1 to 10 |
|||
repeat with n = 1 to 10 |
|||
put n after loopn |
put n after loopn |
||
if n is not 10 then put comma after loopn |
if n is not 10 then put comma after loopn |
||
end repeat |
end repeat |
||
put loopn |
put loopn |
||
</syntaxhighlight> |
|||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
<lang |
<syntaxhighlight lang="logo"> |
||
to comma.list :n |
|||
repeat :n-1 [type repcount type "|, |] |
repeat :n-1 [type repcount type "|, |] |
||
print :n |
print :n |
||
end |
end |
||
comma.list 10 |
comma.list 10 |
||
</syntaxhighlight> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Translation of C: |
Translation of C: |
||
<lang |
<syntaxhighlight lang="lua"> |
||
for i = 1, 10 do |
|||
io.write(i) |
io.write(i) |
||
if i == 10 then break end |
if i == 10 then break end |
||
io.write", " |
io.write", " |
||
end |
end |
||
</syntaxhighlight> |
|||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Checkit { |
Module Checkit { |
||
\\ old type loop |
\\ old type loop |
||
Line 1,377: | Line 2,463: | ||
} |
} |
||
Checkit |
Checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
<syntaxhighlight lang="m4"> |
|||
<lang M4>define(`break', |
|||
define(`break', |
|||
`define(`ulim',llim)') |
`define(`ulim',llim)') |
||
define(`for', |
define(`for', |
||
Line 1,390: | Line 2,476: | ||
for(`x',`1',`', |
for(`x',`1',`', |
||
`x`'ifelse(x,10,`break',`, ')') |
`x`'ifelse(x,10,`break',`, ')') |
||
</syntaxhighlight> |
|||
=={{header|Make}}== |
|||
<syntaxhighlight lang="make"> |
|||
NEXT=`expr $* + 1` |
|||
MAX=10 |
|||
RES=1 |
|||
all: 1-n; |
|||
$(MAX)-n: |
|||
@echo $(RES) |
|||
%-n: |
|||
@-make -f loop.mk $(NEXT)-n MAX=$(MAX) RES=$(RES),$(NEXT) |
|||
</syntaxhighlight> |
|||
Invoking it |
|||
|make -f loop.mk MAX=10 |
|||
1,2,3,4,5,6,7,8,9,10 |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple>> for i to 10 do printf( "%d%s", i, `if`( i = 10, "\n", ", " ) ) end: |
|||
> for i to 10 do printf( "%d%s", i, `if`( i = 10, "\n", ", " ) ) end: |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10</lang> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</syntaxhighlight> |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
<syntaxhighlight lang="mathematica"> |
|||
<lang Mathematica>i = 1; s = ""; |
|||
i = 1; s = ""; |
|||
While[True, |
While[True, |
||
s = s <> ToString@i; |
s = s <> ToString@i; |
||
Line 1,404: | Line 2,513: | ||
i++; |
i++; |
||
] |
] |
||
s |
|||
s</lang> |
|||
</syntaxhighlight> |
|||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
Vectorized form: |
Vectorized form: |
||
<syntaxhighlight lang="matlab"> |
|||
<lang MATLAB> printf('%i, ',1:9); printf('%i\n',10);</lang> |
|||
printf('%i, ',1:9); printf('%i\n',10); |
|||
</syntaxhighlight> |
|||
Explicite loop: |
Explicite loop: |
||
<syntaxhighlight lang="matlab"> |
|||
<lang Matlab> for k=1:10, |
|||
for k=1:10, |
|||
printf('%i', k); |
printf('%i', k); |
||
if k==10, break; end; |
if k==10, break; end; |
||
printf(', '); |
printf(', '); |
||
end; |
end; |
||
printf('\n'); |
printf('\n'); |
||
</syntaxhighlight> |
|||
Output: |
Output: |
||
Line 1,422: | Line 2,536: | ||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
<lang |
<syntaxhighlight lang="maxscript"> |
||
for i in 1 to 10 do |
|||
( |
( |
||
format "%" i |
format "%" i |
||
if i == 10 then exit |
if i == 10 then exit |
||
format "%" ", " |
format "%" ", " |
||
) |
|||
)</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Make}}== |
|||
<lang make>NEXT=`expr $* + 1` |
|||
MAX=10 |
|||
RES=1 |
|||
all: 1-n; |
|||
$(MAX)-n: |
|||
@echo $(RES) |
|||
%-n: |
|||
@-make -f loop.mk $(NEXT)-n MAX=$(MAX) RES=$(RES),$(NEXT)</lang> |
|||
Invoking it |
|||
|make -f loop.mk MAX=10 |
|||
1,2,3,4,5,6,7,8,9,10 |
|||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
Line 1,451: | Line 2,550: | ||
and then we output it. |
and then we output it. |
||
<lang |
<syntaxhighlight lang="metafont"> |
||
last := 10; |
|||
string s; s := ""; |
string s; s := ""; |
||
for i = 1 upto last: |
for i = 1 upto last: |
||
Line 1,458: | Line 2,558: | ||
endfor |
endfor |
||
message s; |
message s; |
||
end |
end |
||
</syntaxhighlight> |
|||
=={{header|min}}== |
|||
min's <code>linrec</code> combinator is flexible enough to easily accomodate this task, due to taking a quotation to execute at the end of the loop (the second one). |
|||
<syntaxhighlight lang="min"> |
|||
1 (dup 10 ==) 'puts! (print succ ", " print!) () linrec |
|||
</syntaxhighlight> |
|||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
<lang |
<syntaxhighlight lang="modula3"> |
||
MODULE Loop EXPORTS Main; |
|||
IMPORT IO, Fmt; |
IMPORT IO, Fmt; |
||
Line 1,475: | Line 2,583: | ||
END; |
END; |
||
IO.Put("\n"); |
IO.Put("\n"); |
||
END Loop. |
END Loop. |
||
</syntaxhighlight> |
|||
=={{header|Nemerle}}== |
|||
<lang Nemerle>foreach (i in [1 .. 10]) |
|||
{ |
|||
Write(i); |
|||
unless (i == 10) Write(", "); |
|||
}</lang> |
|||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
<syntaxhighlight lang="mumps"> |
|||
<lang MUMPS>LOOPHALF |
|||
LOOPHALF |
|||
NEW I |
NEW I |
||
FOR I=1:1:10 DO |
FOR I=1:1:10 DO |
||
Line 1,493: | Line 2,596: | ||
;Alternate |
;Alternate |
||
NEW I FOR I=1:1:10 WRITE I WRITE:I'=10 ", " |
NEW I FOR I=1:1:10 WRITE I WRITE:I'=10 ", " |
||
KILL I QUIT |
KILL I QUIT |
||
</syntaxhighlight> |
|||
Output:<pre>USER>D LOOPHALF^ROSETTA |
Output:<pre>USER>D LOOPHALF^ROSETTA |
||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
Line 1,499: | Line 2,603: | ||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
</pre> |
</pre> |
||
=={{header|Nemerle}}== |
|||
<syntaxhighlight lang="nemerle"> |
|||
foreach (i in [1 .. 10]) |
|||
{ |
|||
Write(i); |
|||
unless (i == 10) Write(", "); |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
<syntaxhighlight lang="netrexx"> |
|||
<lang NetRexx>/* NetRexx */ |
|||
/* NetRexx */ |
|||
/* NetRexx */ |
/* NetRexx */ |
||
options replace format comments java crossref savelog symbols nobinary |
options replace format comments java crossref savelog symbols nobinary |
||
Line 1,517: | Line 2,631: | ||
end |
end |
||
end i_ |
end i_ |
||
say rs.strip() |
say rs.strip() |
||
</syntaxhighlight> |
|||
'''Output''' |
'''Output''' |
||
<pre>Loops/N plus one half |
<pre>Loops/N plus one half |
||
Line 1,523: | Line 2,638: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
<syntaxhighlight lang="newlisp"> |
|||
<lang NewLISP>(for (i 0 10) |
|||
(for (i 0 10) |
|||
(print i) |
(print i) |
||
(unless (= i 10) |
(unless (= i 10) |
||
(print ", "))) |
(print ", "))) |
||
</syntaxhighlight> |
|||
=={{header| |
=={{header|Nim}}== |
||
<syntaxhighlight lang="nim"> |
|||
<lang smallbasic>For i = 1 To 10 |
|||
var s = "" |
|||
TextWindow.Write(i) |
|||
for i in 1..10: |
|||
s.add $i |
|||
TextWindow.Write(", ") |
|||
if i == 10: break |
|||
EndIf |
|||
s.add ", " |
|||
EndFor |
|||
echo s |
|||
TextWindow.WriteLine("")</lang> |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
=={{header| |
=={{header|Nu}}== |
||
<lang |
<syntaxhighlight lang="nu"> |
||
for i in 1.. { |
|||
print -n $i |
|||
if $i == 10 { |
|||
print "" |
|||
break |
|||
} |
|||
print -n ", " |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
for i in 1..10: |
|||
if s.len > 0: s.add(", ") |
|||
s.add($i) |
|||
=={{header|Oberon-07}}== |
|||
echo s</lang> |
|||
===Using a FOR loop=== |
|||
Should also work with Oberon-2. |
|||
<syntaxhighlight lang="modula2"> |
|||
MODULE LoopsNPlusOneHalf1; |
|||
IMPORT Out; |
|||
VAR i :INTEGER; |
|||
BEGIN |
|||
FOR i := 1 TO 10 DO |
|||
Out.Int( i, 0 ); |
|||
IF i < 10 THEN Out.String( ", " ) END |
|||
END |
|||
END LoopsNPlusOneHalf1. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
===Using an extended WHILE loop=== |
|||
Whilst probably not the best way of handling the task, this example demonstrates the extended WHILE loop available in Oberon-07.<br/> |
|||
The WHILE loop can have multiple conditions and DO pats. The conditions following WHILE and ELSIF are evaluated in order and the DO part corresponding to the first TRUE one is executed.<br/> |
|||
The loop terminates when all the conditions evaluate to FALSE |
|||
<syntaxhighlight lang="modula2"> |
|||
MODULE LoopsNPlusOneHalf; |
|||
IMPORT Out; |
|||
VAR i :INTEGER; |
|||
BEGIN |
|||
i := 0; |
|||
WHILE i < 9 DO |
|||
i := i + 1; |
|||
Out.Int( i, 0 ); |
|||
Out.String( ", " ) |
|||
ELSIF i < 10 DO |
|||
i := i + 1; |
|||
Out.Int( i, 0 ) |
|||
END |
|||
END LoopsNPlusOneHalf. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class Hello { |
class Hello { |
||
Line 1,563: | Line 2,739: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
<lang |
<syntaxhighlight lang="ocaml"> |
||
let last = 10 in |
|||
for i = 1 to last do |
for i = 1 to last do |
||
print_int i; |
print_int i; |
||
Line 1,572: | Line 2,749: | ||
print_string ", "; |
print_string ", "; |
||
done; |
done; |
||
print_newline(); |
print_newline(); |
||
</syntaxhighlight> |
|||
<syntaxhighlight lang="ocaml"> |
|||
<lang ocaml>let ints = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] in |
|||
let ints = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] in |
|||
let str_ints = List.map string_of_int ints in |
let str_ints = List.map string_of_int ints in |
||
print_endline (String.concat ", " str_ints); |
print_endline (String.concat ", " str_ints); |
||
</syntaxhighlight> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
<syntaxhighlight lang="oforth"> |
|||
<lang Oforth>: loopn |
|||
: loopn |
|||
| i | |
| i | |
||
10 loop: i [ i dup print 10 ifEq: [ break ] "," . ] printcr ; |
10 loop: i [ i dup print 10 ifEq: [ break ] "," . ] printcr ; |
||
</syntaxhighlight> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
Using a for-loop: |
Using a for-loop: |
||
<syntaxhighlight lang="oz"> |
|||
<lang oz> |
|||
for N in {List.number 1 10 1} break:Break do |
for N in {List.number 1 10 1} break:Break do |
||
{System.printInfo N} |
{System.printInfo N} |
||
if N == 10 then {Break} end |
if N == 10 then {Break} end |
||
{System.printInfo ", "} |
{System.printInfo ", "} |
||
end |
end |
||
</syntaxhighlight> |
|||
However, it seems more natural to use a left fold: |
However, it seems more natural to use a left fold: |
||
<syntaxhighlight lang="oz"> |
|||
<lang oz>declare |
|||
declare |
|||
fun {CommaSep Xs} |
fun {CommaSep Xs} |
||
case Xs of nil then nil |
case Xs of nil then nil |
||
Line 1,604: | Line 2,788: | ||
end |
end |
||
in |
in |
||
{System.showInfo {CommaSep {List.number 1 10 1}}} |
{System.showInfo {CommaSep {List.number 1 10 1}}} |
||
</syntaxhighlight> |
|||
=={{header|Panda}}== |
|||
Panda is stream based. To know if there is no more values you need to know it's the last. You can only do that if you get all the values. So this is functional style; We accumulate all the values from the stream. Then join them together as strings with a comma. |
|||
<syntaxhighlight lang="panda"> |
|||
array{{1..10}}.join(',') |
|||
</syntaxhighlight> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp"> |
||
n=0; |
|||
while(1, |
while(1, |
||
print1(n++); |
print1(n++); |
||
if(n>9, break); |
if(n>9, break); |
||
print1(", ") |
print1(", ") |
||
); |
); |
||
</syntaxhighlight> |
|||
=={{header|Panda}}== |
|||
Panda is stream based. To know if there is no more values you need to know it's the last. You can only do that if you get all the values. So this is functional style; We accumulate all the values from the stream. Then join them together as strings with a comma. |
|||
<lang panda>array{{1..10}}.join(',')</lang> |
|||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
<lang |
<syntaxhighlight lang="pascal"> |
||
program numlist(output); |
|||
const MAXNUM: integer = 10; |
const MAXNUM: integer = 10; |
||
Line 1,638: | Line 2,828: | ||
write(i, ', '); |
write(i, ', '); |
||
writeln(MAXNUM); |
writeln(MAXNUM); |
||
end. |
end. |
||
</syntaxhighlight> |
|||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
## |
|||
for var i:=1 to 10 do |
|||
Write(i, i = 10 ? '' : ', '); |
|||
</syntaxhighlight> |
|||
=={{header|Peloton}}== |
=={{header|Peloton}}== |
||
<syntaxhighlight lang="sgml"> |
|||
<lang sgml><@ FORLITLIT>10|<@ SAYPOSFOR>...</@><@ ABF>,</@></@></lang> |
|||
<@ FORLITLIT>10|<@ SAYPOSFOR>...</@><@ ABF>,</@></@> |
|||
</syntaxhighlight> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
<lang |
<syntaxhighlight lang="perl"> |
||
for my $i(1..10) { |
|||
print $i; |
print $i; |
||
last if $i == 10; |
last if $i == 10; |
||
print ', '; |
print ', '; |
||
} |
} |
||
print "\n"; |
print "\n"; |
||
</syntaxhighlight> |
|||
In perl one would solve the task via <code>join</code>. |
In perl one would solve the task via <code>join</code>. |
||
<syntaxhighlight lang="perl"> |
|||
<lang perl>print join(', ', 1..10), "\n";</lang> |
|||
print join(', ', 1..10), "\n"; |
|||
</syntaxhighlight> |
|||
=={{header| |
=={{header|Phix}}== |
||
<!--<syntaxhighlight lang="phix"> |
|||
<lang perl6>for 1 .. 10 { |
|||
--> |
|||
.print; |
|||
<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;">10</span> <span style="color: #008080;">do</span> |
|||
last when 10; |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> |
|||
print ', '; |
|||
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">10</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
} |
|||
<span style="color: #7060A8;">printf</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> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<!-- |
|||
</syntaxhighlight>--> |
|||
=={{header|Phixmonti}}== |
|||
print "\n";</lang> |
|||
<syntaxhighlight lang="Phixmonti"> |
|||
/# Rosetta Code problem: https://rosettacode.org/wiki/Loops/N_plus_one_half |
|||
by Galileo, 11/2022 #/ |
|||
10 for dup print 10 == not if ", " print endif endfor |
|||
=={{header|Phix}}== |
|||
</syntaxhighlight> |
|||
<lang Phix>for i=1 to 10 do |
|||
{{out}} |
|||
printf(1,"%d",i) |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
=== Press any key to exit ===</pre> |
|||
printf(1,", ") |
|||
end for</lang> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
<syntaxhighlight lang="php"> |
|||
<lang php>for ($i = 1; $i <= 11; $i++) { |
|||
for ($i = 1; $i <= 11; $i++) { |
|||
echo $i; |
echo $i; |
||
if ($i == 10) |
if ($i == 10) |
||
Line 1,677: | Line 2,890: | ||
echo ', '; |
echo ', '; |
||
} |
} |
||
echo "\n"; |
echo "\n"; |
||
</syntaxhighlight> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
<syntaxhighlight lang="picolisp"> |
|||
<lang PicoLisp>(for N 10 |
|||
(for N 10 |
|||
(prin N) |
(prin N) |
||
(T (= N 10)) |
(T (= N 10)) |
||
(prin ", ") ) |
(prin ", ") ) |
||
</syntaxhighlight> |
|||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike"> |
||
int main(){ |
int main(){ |
||
for(int i = 1; i <= 11; i++){ |
for(int i = 1; i <= 11; i++){ |
||
Line 1,696: | Line 2,912: | ||
} |
} |
||
write("\n"); |
write("\n"); |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
The most idiomatic way of inserting delimiters in Pike is the multiplication operator and it's symmetry with division of strings. |
|||
<syntaxhighlight lang="text"> |
|||
> "1, 2, 3"/", "; |
|||
Result: ({ "1", "2", "3" }) |
|||
> ({ "1", "2", "3" })*", "; |
|||
Result: "1, 2, 3" |
|||
</syntaxhighlight> |
|||
So achieving the result of this task with the method more suited to |
|||
Pike would be: |
|||
<syntaxhighlight lang="text"> |
|||
array a = (array(string))enumerate(10, 1, 1); |
|||
write(a * ", " + "\n"); |
|||
</syntaxhighlight> |
|||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
do i = 1 to 10; |
do i = 1 to 10; |
||
put edit (trim(i)) (a); |
put edit (trim(i)) (a); |
||
if i < 10 then put edit (', ') (a); |
if i < 10 then put edit (', ') (a); |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Plain English}}== |
|||
<syntaxhighlight lang="plainenglish"> |
|||
To run: |
|||
Start up. |
|||
Write the numbers up to 10 on the console. |
|||
Wait for the escape key. |
|||
Shut down. |
|||
To write the numbers up to a number on the console: |
|||
If a counter is past the number, exit. |
|||
Convert the counter to a string. |
|||
Write the string on the console without advancing. |
|||
If the counter is less than the number, write ", " on the console without advancing. |
|||
Repeat. |
|||
</syntaxhighlight> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
<lang |
<syntaxhighlight lang="pop11"> |
||
lvars i; |
|||
for i from 1 to 10 do |
for i from 1 to 10 do |
||
printf(i, '%p'); |
printf(i, '%p'); |
||
Line 1,713: | Line 2,962: | ||
printf(', ', '%p'); |
printf(', ', '%p'); |
||
endfor; |
endfor; |
||
printf('\n', '%p'); |
printf('\n', '%p'); |
||
</syntaxhighlight> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
{{trans|C}} |
{{trans|C}} |
||
<lang |
<syntaxhighlight lang="powershell"> |
||
for ($i = 1; $i -le 10; $i++) { |
|||
Write-Host -NoNewLine $i |
Write-Host -NoNewLine $i |
||
if ($i -eq 10) { |
if ($i -eq 10) { |
||
Line 1,724: | Line 2,975: | ||
} |
} |
||
Write-Host -NoNewLine ", " |
Write-Host -NoNewLine ", " |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
An interesting alternative solution, although not ''strictly'' a loop, even though <code>switch</code> certainly loops over the given range. |
An interesting alternative solution, although not ''strictly'' a loop, even though <code>switch</code> certainly loops over the given range. |
||
<lang |
<syntaxhighlight lang="powershell"> |
||
switch (1..10) { |
|||
{ $true } { Write-Host -NoNewLine $_ } |
{ $true } { Write-Host -NoNewLine $_ } |
||
{ $_ -lt 10 } { Write-Host -NoNewLine ", " } |
{ $_ -lt 10 } { Write-Host -NoNewLine ", " } |
||
{ $_ -eq 10 } { Write-Host } |
{ $_ -eq 10 } { Write-Host } |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|PureBasic}}== |
|||
<lang PureBasic>x=1 |
|||
Repeat |
|||
Print(Str(x)) |
|||
x+1 |
|||
If x>10: Break: EndIf |
|||
Print(", ") |
|||
ForEver</lang> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
<lang |
<syntaxhighlight lang="prolog"> |
||
example :- |
|||
between(1,10,Val), write(Val), Val<10, write(', '), fail. |
between(1,10,Val), write(Val), Val<10, write(', '), fail. |
||
example. |
example. |
||
</syntaxhighlight> |
|||
<pre>?- example. |
<pre>?- example. |
||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
true.</pre> |
true.</pre> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
The particular pattern and example chosen in the task description is recognised by the Python language and there are more idiomatic ways to achieve the result that don't even require an explicit conditional test such as: |
The particular pattern and example chosen in the task description is recognised by the Python language and there are more idiomatic ways to achieve the result that don't even require an explicit conditional test such as: |
||
<syntaxhighlight lang="python"> |
|||
<lang python>print ( ', '.join(str(i+1) for i in range(10)) )</lang> |
|||
print ( ', '.join(str(i+1) for i in range(10)) ) |
|||
</syntaxhighlight> |
|||
But the [http://academicearth.org/lectures/the-loop-and-half-problem named pattern] is shown by code such as the following: |
But the [http://academicearth.org/lectures/the-loop-and-half-problem named pattern] is shown by code such as the following: |
||
<lang |
<syntaxhighlight lang="python"> |
||
>>> from sys import stdout |
|||
>>> write = stdout.write |
>>> write = stdout.write |
||
>>> n, i = 10, 1 |
>>> n, i = 10, 1 |
||
Line 1,765: | Line 3,015: | ||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
>> |
>>> |
||
</syntaxhighlight> |
|||
List comprehension one-liner |
|||
<syntaxhighlight lang="python"> |
|||
[print(str(i+1) + ", ",end='') if i < 9 else print(i+1) for i in range(10)] |
|||
</syntaxhighlight> |
|||
{{works with|Python|3.x}} |
|||
<syntaxhighlight lang="python"> |
|||
n, i = 10, 1 |
|||
while True: |
|||
print(i, end="") |
|||
i += 1 |
|||
if i > n: |
|||
break |
|||
print(", ", end="") |
|||
</syntaxhighlight> |
|||
=={{header|Quackery}}== |
|||
<syntaxhighlight lang="quackery"> |
|||
10 times |
|||
[ i^ 1+ echo |
|||
i 0 = iff |
|||
conclude done |
|||
say ", " ] |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
The natural way to solve this task in R is: |
The natural way to solve this task in R is: |
||
<syntaxhighlight lang="r"> |
|||
<lang R>paste(1:10, collapse=", ")</lang> |
|||
paste(1:10, collapse=", ") |
|||
</syntaxhighlight> |
|||
The task specifies that we should use a loop however, so this more verbose code is needed. |
The task specifies that we should use a loop however, so this more verbose code is needed. |
||
<syntaxhighlight lang="r"> |
|||
<lang R>for(i in 1:10) |
|||
for(i in 1:10) |
|||
{ |
{ |
||
cat(i) |
cat(i) |
||
Line 1,780: | Line 3,064: | ||
} |
} |
||
cat(", ") |
cat(", ") |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
|||
(for ((i (in-range 1 15))) |
(for ((i (in-range 1 15))) |
||
(display i) |
(display i) |
||
#:break (= 10 i) |
#:break (= 10 i) |
||
(display ", ")) |
(display ", ")) |
||
</syntaxhighlight> |
|||
Gives the desired output. |
Gives the desired output. |
||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
<syntaxhighlight lang="raku" line>for 1 .. 10 { |
|||
.print; |
|||
last when 10; |
|||
print ', '; |
|||
} |
|||
print "\n"; |
|||
</syntaxhighlight> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
<syntaxhighlight lang="rebol"> |
|||
<lang REBOL>REBOL [ |
|||
REBOL [ |
|||
Title: "Loop Plus Half" |
Title: "Loop Plus Half" |
||
URL: http://rosettacode.org/wiki/Loop/n_plus_one_half |
URL: http://rosettacode.org/wiki/Loop/n_plus_one_half |
||
Line 1,802: | Line 3,101: | ||
prin ", " |
prin ", " |
||
] |
] |
||
print "" |
print "" |
||
</syntaxhighlight> |
|||
=={{header|Red}}== |
|||
<syntaxhighlight lang="rebol"> |
|||
Red[] |
|||
repeat i 10 [ |
|||
prin i |
|||
if 10 = i [break] |
|||
prin ", " |
|||
] |
|||
print "" |
|||
</syntaxhighlight> |
|||
=={{header|Relation}}== |
|||
<syntaxhighlight lang="relation"> |
|||
set i = 1 |
|||
set result = "" |
|||
while i <= 10 |
|||
set result = result . i |
|||
if i < 10 |
|||
set result = result . ", " |
|||
end if |
|||
set i = i + 1 |
|||
end while |
|||
echo result |
|||
</syntaxhighlight> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===two CHAROUTs=== |
===two CHAROUTs=== |
||
<syntaxhighlight lang="rexx"> |
|||
<lang rexx>/*REXX program displays: 1,2,3,4,5,6,7,8,9,10 */ |
|||
/*REXX program displays: 1,2,3,4,5,6,7,8,9,10 */ |
|||
do j=1 to 10 |
do j=1 to 10 |
||
Line 1,812: | Line 3,139: | ||
if j<10 then call charout ,"," /*append a comma for one-digit numbers.*/ |
if j<10 then call charout ,"," /*append a comma for one-digit numbers.*/ |
||
end /*j*/ |
end /*j*/ |
||
/*stick a fork in it, we're all done. */ |
/*stick a fork in it, we're all done. */ |
||
</syntaxhighlight> |
|||
'''output''' |
'''output''' |
||
<pre> |
<pre> |
||
Line 1,819: | Line 3,147: | ||
===one CHAROUT=== |
===one CHAROUT=== |
||
<syntaxhighlight lang="rexx"> |
|||
<lang rexx>/*REXX program displays: 1,2,3,4,5,6,7,8,9,10 */ |
|||
/*REXX program displays: 1,2,3,4,5,6,7,8,9,10 */ |
|||
do j=1 for 10 /*using FOR is faster than TO. */ |
do j=1 for 10 /*using FOR is faster than TO. */ |
||
call charout ,j || left(',',j<10) /*display J, maybe append a comma (,).*/ |
call charout ,j || left(',',j<10) /*display J, maybe append a comma (,).*/ |
||
end /*j*/ |
end /*j*/ |
||
/*stick a fork in it, we're all done. */ |
/*stick a fork in it, we're all done. */ |
||
</syntaxhighlight> |
|||
'''output''' |
'''output''' |
||
<pre> |
<pre> |
||
Line 1,831: | Line 3,161: | ||
===version 3 if the number of items is not known=== |
===version 3 if the number of items is not known=== |
||
<lang |
<syntaxhighlight lang="rexx"> |
||
list='aa bb cc dd' |
|||
sep=', ' |
sep=', ' |
||
Do i=1 By 1 While list<>'' |
Do i=1 By 1 While list<>'' |
||
Line 1,837: | Line 3,168: | ||
Parse Var list item list |
Parse Var list item list |
||
Call charout ,item |
Call charout ,item |
||
End |
End |
||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre>aa, bb, cc, dd</pre> |
<pre>aa, bb, cc, dd</pre> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
for x = 1 to 10 see x if x=10 exit ok see ", " next see nl |
for x = 1 to 10 see x if x=10 exit ok see ", " next see nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
There are basically 2 possibilities, based on an overarching <code>FOR..NEXT</code> or <code>DO..UNTIL</code> / <code>WHILE..REPEAT</code> loop structure, in which an <code>IF..THEN..ELSE</code> decides which parts of the loop must be executed. RPL does not have any instruction to just exit a loop. |
|||
The <code>DO..UNTIL</code> / <code>WHILE..REPEAT</code> approach requires to use a flag and to manage a counter, which weighs down the code, as it can be seen in the implementations below. |
|||
≪ "" |
|||
1 10 '''FOR''' j |
|||
j →STR + |
|||
'''IF''' j 10 < '''THEN''' ", " + '''END''' |
|||
'''NEXT''' |
|||
≫ 'S1→10' STO |
|||
17 words |
|||
≪ 1 CF "" 0 |
|||
'''DO''' |
|||
1 + SWAP OVER →STR + |
|||
'''IF''' OVER 10 < '''THEN''' ", " + '''ELSE''' 1 SF '''END''' |
|||
SWAP |
|||
'''UNTIL''' 1 FS? '''END''' |
|||
DROP |
|||
≫ 'S1→10' STO |
|||
28 words + 1 flag |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby"> |
||
(1..10).each do |i| |
(1..10).each do |i| |
||
print i |
print i |
||
Line 1,853: | Line 3,206: | ||
print ", " |
print ", " |
||
end |
end |
||
puts |
puts |
||
</syntaxhighlight> |
|||
More idiomatic Ruby to obtain the same result is: |
More idiomatic Ruby to obtain the same result is: |
||
< |
<syntaxhighlight lang="ruby"> |
||
puts (1..10).join(", ") |
puts (1..10).join(", ") |
||
</syntaxhighlight> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
<lang |
<syntaxhighlight lang="rust"> |
||
fn main() { |
|||
for i in 1..11 { |
|||
for i in 1..=10 { |
|||
print!("{}{}", i, if i < 10 { ", " } else { "\n" }); |
|||
} |
} |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
More like the problem description: |
|||
=={{header|Run BASIC}}== |
|||
<syntaxhighlight lang="rust"> |
|||
<lang runbasic> |
|||
fn main() { |
|||
FOR i = 1 TO 10 |
|||
for i in 1..=10 { |
|||
PRINT cma$;i; |
|||
print!("{}", i); |
|||
if i == 10 { |
|||
NEXT i |
|||
break; |
|||
</lang> |
|||
} |
|||
print!(", "); |
|||
} |
|||
println!(); |
|||
} |
|||
</syntaxhighlight> |
|||
Alternative solution using <code>join</code>. |
|||
<syntaxhighlight lang="rust"> |
|||
fn main() { |
|||
println!( |
|||
"{}", |
|||
(1..=10) |
|||
.map(|i| i.to_string()) |
|||
.collect::<Vec<_>>() |
|||
.join(", ") |
|||
); |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|S-lang}}== |
=={{header|S-lang}}== |
||
Line 1,878: | Line 3,254: | ||
part from the bottom to the top of the loop, then NOT include it on the |
part from the bottom to the top of the loop, then NOT include it on the |
||
FIRST pass: |
FIRST pass: |
||
<lang |
<syntaxhighlight lang="s-lang"> |
||
variable more = 0, i; |
|||
foreach i ([1:10]) { |
foreach i ([1:10]) { |
||
if (more) () = printf(", "); |
if (more) () = printf(", "); |
||
printf("%d", i); |
printf("%d", i); |
||
more = 1; |
more = 1; |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Salmon}}== |
=={{header|Salmon}}== |
||
<syntaxhighlight lang="salmon"> |
|||
<lang Salmon>iterate (x; [1...10]) |
|||
iterate (x; [1...10]) |
|||
{ |
{ |
||
print(x); |
print(x); |
||
Line 1,893: | Line 3,272: | ||
print(", "); |
print(", "); |
||
}; |
}; |
||
print("\n"); |
print("\n"); |
||
</syntaxhighlight> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
{{libheader|Scala}} |
{{libheader|Scala}} |
||
<syntaxhighlight lang="scala"> |
|||
<lang Scala>object LoopAndHalf extends App { |
|||
var i = 1 |
|||
println((1 to 10).mkString(", ")) |
|||
while ({ |
|||
}</lang> |
|||
print(i) |
|||
i < 10 |
|||
}) { |
|||
print(", ") |
|||
i += 1 |
|||
} |
|||
println() |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="scala"> |
|||
println((1 to 10).mkString(", ")) |
|||
</syntaxhighlight> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
It is possible to use continuations: |
It is possible to use continuations: |
||
<syntaxhighlight lang="scheme"> |
|||
<lang scheme>(call-with-current-continuation |
|||
(call-with-current-continuation |
|||
(lambda (esc) |
(lambda (esc) |
||
(do ((i 1 (+ 1 i))) (#f) |
(do ((i 1 (+ 1 i))) (#f) |
||
(display i) |
(display i) |
||
(if (= i 10) (esc (newline))) |
(if (= i 10) (esc (newline))) |
||
(display ", ")))) |
(display ", ")))) |
||
</syntaxhighlight> |
|||
But usually making the tail recursion explicit is enough: |
But usually making the tail recursion explicit is enough: |
||
<lang |
<syntaxhighlight lang="scheme"> |
||
(let loop ((i 0)) |
|||
(display i) |
(display i) |
||
(if (= i 10) |
(if (= i 10) |
||
Line 1,917: | Line 3,311: | ||
(begin |
(begin |
||
(display ", ") |
(display ", ") |
||
(loop (+ 1 i))))) |
(loop (+ 1 i))))) |
||
</syntaxhighlight> |
|||
=={{header|Scilab}}== |
=={{header|Scilab}}== |
||
{{works with|Scilab|5.5.1}} |
{{works with|Scilab|5.5.1}} |
||
<syntaxhighlight lang="text"> |
|||
<lang>for i=1:10 |
|||
for i=1:10 |
|||
printf("%2d ",i) |
printf("%2d ",i) |
||
if i<10 then printf(", "); end |
if i<10 then printf(", "); end |
||
end |
end |
||
printf("\n") |
printf("\n") |
||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre> 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 </pre> |
<pre> 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 </pre> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
<syntaxhighlight lang="seed7"> |
|||
<lang seed7>$ include "seed7_05.s7i"; |
|||
$ include "seed7_05.s7i"; |
|||
const proc: main is func |
const proc: main is func |
||
Line 1,943: | Line 3,341: | ||
end for; |
end for; |
||
writeln; |
writeln; |
||
end func; |
end func; |
||
</syntaxhighlight> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
<lang |
<syntaxhighlight lang="ruby"> |
||
for (1..10) { |i| |
|||
print i; |
print i; |
||
i == 10 && break; |
i == 10 && break; |
||
Line 1,952: | Line 3,352: | ||
} |
} |
||
print "\n"; |
print "\n"; |
||
</syntaxhighlight> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
<lang |
<syntaxhighlight lang="smalltalk"> |
||
1 to: 10 do: [:n | |
|||
Transcript show: n asString. |
Transcript show: n asString. |
||
n < 10 ifTrue: [ Transcript show: ', ' ] |
n < 10 ifTrue: [ Transcript show: ', ' ] |
||
] |
|||
]</lang> |
|||
</syntaxhighlight> |
|||
Smalltalk/X and Pharo/Squeak have special enumeration messages for this in their Collection class, which executes another action in-between iterated elements: |
|||
{{works with|Smalltalk/X}}{{works with|Pharo}} |
|||
<syntaxhighlight lang="smalltalk"> |
|||
(1 to: 10) do: [:n | |
|||
Transcript show: n asString. |
|||
] separatedBy:[ |
|||
Transcript show: ', ' |
|||
] |
|||
</syntaxhighlight> |
|||
That is a bit different from the task's specification, but does what is needed here, and is more general in working with any collection (in the above case: a range aka "Interval"). It does not depend on the collection being addressed by an integer index and/or keeping a count inside the loop. |
|||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Line 1,965: | Line 3,378: | ||
line output, and to use the same statement for loop control and the comma. |
line output, and to use the same statement for loop control and the comma. |
||
<syntaxhighlight lang="snobol4"> |
|||
<lang SNOBOL4>loop str = str lt(i,10) (i = i + 1) :f(out) |
|||
loop str = str lt(i,10) (i = i + 1) :f(out) |
|||
str = str ne(i,10) ',' :s(loop) |
str = str ne(i,10) ',' :s(loop) |
||
out output = str |
out output = str |
||
end |
end |
||
</syntaxhighlight> |
|||
{{works with|Macro Spitbol}} |
{{works with|Macro Spitbol}} |
||
Line 1,976: | Line 3,391: | ||
This example also breaks the loop explicitly: |
This example also breaks the loop explicitly: |
||
<syntaxhighlight lang="snobol4"> |
|||
<lang SNOBOL4> output('out',1,'-[-r1]') |
|||
output('out',1,'-[-r1]') |
|||
loop i = lt(i,10) i + 1 :f(end) |
loop i = lt(i,10) i + 1 :f(end) |
||
out = i |
out = i |
||
eq(i,10) :s(end) |
eq(i,10) :s(end) |
||
out = ',' :(loop) |
out = ',' :(loop) |
||
end |
end |
||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
Line 1,987: | Line 3,404: | ||
=={{header|SNUSP}}== |
=={{header|SNUSP}}== |
||
<syntaxhighlight lang="snusp"> |
|||
<lang snusp>@\>@\>@\>+++++++++<!/+. >-?\# digit and loop test |
|||
@\>@\>@\>+++++++++<!/+. >-?\# digit and loop test |
|||
| | \@@@+@+++++# \>>.<.<</ comma and space |
| | \@@@+@+++++# \>>.<.<</ comma and space |
||
| \@@+@@+++++# |
| \@@+@@+++++# |
||
\@@@@=++++# |
\@@@@=++++# |
||
</syntaxhighlight> |
|||
=={{header|Spin}}== |
|||
{{works with|BST/BSTC}} |
|||
{{works with|FastSpin/FlexSpin}} |
|||
{{works with|HomeSpun}} |
|||
{{works with|OpenSpin}} |
|||
<syntaxhighlight lang="spin"> |
|||
con |
|||
_clkmode = xtal1 + pll16x |
|||
_clkfreq = 80_000_000 |
|||
obj |
|||
ser : "FullDuplexSerial.spin" |
|||
pub main | n |
|||
ser.start(31, 30, 0, 115200) |
|||
repeat n from 1 to 10 |
|||
ser.dec(n) |
|||
if n<10 |
|||
ser.str(string(", ")) |
|||
ser.str(string(13, 10)) |
|||
waitcnt(_clkfreq + cnt) |
|||
ser.stop |
|||
cogstop(0) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
<lang |
<syntaxhighlight lang="stata"> |
||
forv i=1/10 { |
|||
di `i' _continue |
di `i' _continue |
||
if `i'<10 { |
if `i'<10 { |
||
Line 2,001: | Line 3,452: | ||
di |
di |
||
} |
} |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=== Mata === |
=== Mata === |
||
< |
<syntaxhighlight lang="stata"> |
||
mata |
|||
for (i=1; i<=10; i++) { |
for (i=1; i<=10; i++) { |
||
printf("%f",i) |
printf("%f",i) |
||
Line 2,013: | Line 3,466: | ||
} |
} |
||
} |
} |
||
end |
end |
||
</syntaxhighlight> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
{{works with|Swift|1.x}} |
{{works with|Swift|1.x}} |
||
<lang |
<syntaxhighlight lang="swift"> |
||
for var i = 1; ; i++ { |
|||
print(i) |
print(i) |
||
if i == 10 { |
if i == 10 { |
||
Line 2,024: | Line 3,479: | ||
} |
} |
||
print(", ") |
print(", ") |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
{{works with|Swift|2}} The usual way to do this with Swift 2 is: |
{{works with|Swift|2}} The usual way to do this with Swift 2 is: |
||
< |
<syntaxhighlight lang="swift"> |
||
for i in 1...10 { |
for i in 1...10 { |
||
print(i, terminator: i == 10 ? "\n" : ", ") |
print(i, terminator: i == 10 ? "\n" : ", ") |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
To satisfy the specification, we have to do something similar to Swift 1.x and other C-like languages: |
To satisfy the specification, we have to do something similar to Swift 1.x and other C-like languages: |
||
<lang |
<syntaxhighlight lang="swift"> |
||
for var i = 1; ; i++ { |
|||
print(i, terminator: "") |
print(i, terminator: "") |
||
if i == 10 { |
if i == 10 { |
||
Line 2,040: | Line 3,497: | ||
} |
} |
||
print(", ", terminator: "") |
print(", ", terminator: "") |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
<syntaxhighlight lang="tcl"> |
|||
<lang tcl>for {set i 1; set end 10} true {incr i} { |
|||
for {set i 1; set end 10} true {incr i} { |
|||
puts -nonewline $i |
puts -nonewline $i |
||
if {$i >= $end} break |
if {$i >= $end} break |
||
puts -nonewline ", " |
puts -nonewline ", " |
||
} |
} |
||
puts "" |
puts "" |
||
</syntaxhighlight> |
|||
However, that's not how the specific task (printing 1..10 with comma separators) would normally be done. (Note, the solution below is ''not'' a solution to the half-looping problem.) |
However, that's not how the specific task (printing 1..10 with comma separators) would normally be done. (Note, the solution below is ''not'' a solution to the half-looping problem.) |
||
<syntaxhighlight lang="tcl"> |
|||
<lang tcl>proc range {from to} { |
|||
proc range {from to} { |
|||
set result {} |
set result {} |
||
for {set i $from} {$i <= $to} {incr i} { |
for {set i $from} {$i <= $to} {incr i} { |
||
Line 2,058: | Line 3,519: | ||
} |
} |
||
puts [join [range 1 10] ", "] ;# ==> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
puts [join [range 1 10] ", "] ;# ==> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
</syntaxhighlight> |
|||
=={{header|TI-89 BASIC}}== |
|||
There is no horizontal cursor position on the program IO screen, so we concatenate strings instead. |
|||
<lang ti89b>Local str |
|||
"" → str |
|||
For i,1,10 |
|||
str & string(i) → str |
|||
If i < 10 Then |
|||
str & "," → str |
|||
EndIf |
|||
EndFor |
|||
Disp str</lang> |
|||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
line="" |
line="" |
||
Line 2,083: | Line 3,531: | ||
ENDLOOP |
ENDLOOP |
||
PRINT line |
PRINT line |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
||
</pre> |
</pre> |
||
=={{header|UnixPipes}}== |
|||
The last iteration is handled automatically for us |
|||
when there is no element in one of the pipes. |
|||
<lang bash>yes \ | cat -n | head -n 10 | paste -d\ - <(yes , | head -n 9) | xargs echo</lang> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
<syntaxhighlight lang="bash"> |
|||
<lang bash>for(( Z=1; Z<=10; Z++ )); do |
|||
for(( Z=1; Z<=10; Z++ )); do |
|||
echo -e "$Z\c" |
echo -e "$Z\c" |
||
if (( Z != 10 )); then |
if (( Z != 10 )); then |
||
echo -e ", \c" |
echo -e ", \c" |
||
fi |
fi |
||
done |
done |
||
</syntaxhighlight> |
|||
{{works with|Bash}} |
{{works with|Bash}} |
||
<syntaxhighlight lang="bash"> |
|||
<lang bash>for ((i=1;i<=$((last=10));i++)); do |
|||
for ((i=1;i<=$((last=10));i++)); do |
|||
echo -n $i |
echo -n $i |
||
[ $i -eq $last ] && break |
[ $i -eq $last ] && break |
||
echo -n ", " |
echo -n ", " |
||
done |
done |
||
</syntaxhighlight> |
|||
=={{header|UnixPipes}}== |
|||
The last iteration is handled automatically for us |
|||
when there is no element in one of the pipes. |
|||
<syntaxhighlight lang="bash"> |
|||
yes \ | cat -n | head -n 10 | paste -d\ - <(yes , | head -n 9) | xargs echo |
|||
</syntaxhighlight> |
|||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
{{trans|PHP}} |
{{trans|PHP}} |
||
<lang |
<syntaxhighlight lang="ursa"> |
||
decl int i |
|||
for (set i 1) (< i 11) (inc i) |
for (set i 1) (< i 11) (inc i) |
||
out i console |
out i console |
||
Line 2,119: | Line 3,574: | ||
out ", " console |
out ", " console |
||
end for |
end for |
||
out endl console |
out endl console |
||
</syntaxhighlight> |
|||
=={{header|V}}== |
=={{header|V}}== |
||
<lang |
<syntaxhighlight lang="v"> |
||
[loop |
|||
[ [10 =] [puts] |
[ [10 =] [puts] |
||
[true] [dup put ',' put succ loop] |
[true] [dup put ',' put succ loop] |
||
] when]. |
] when]. |
||
</syntaxhighlight> |
|||
Using it |
Using it |
||
|1 loop |
|1 loop |
||
=1,2,3,4,5,6,7,8,9,10 |
=1,2,3,4,5,6,7,8,9,10 |
||
=={{header| |
=={{header|Vala}}== |
||
{{trans|C}} |
|||
<lang VB>Public Sub WriteACommaSeparatedList() |
|||
<syntaxhighlight lang="vala"> |
|||
Dim i As Integer |
|||
void main() { |
|||
Dim a(1 To 10) As String |
|||
for (int i = 1; i <= 10; i++) |
|||
{ |
|||
a(i) = CStr(i) |
|||
stdout.printf("%d", i); |
|||
stdout.printf(i == 10 ? "\n" : ", "); |
|||
} |
|||
End Sub</lang> |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Vedit macro language}}== |
=={{header|Vedit macro language}}== |
||
This example writes the output into current edit buffer. |
This example writes the output into current edit buffer. |
||
<lang |
<syntaxhighlight lang="vedit"> |
||
for (#1 = 1; 1; #1++) { |
|||
Num_Ins(#1, LEFT+NOCR) |
Num_Ins(#1, LEFT+NOCR) |
||
if (#1 == 10) { Break } |
if (#1 == 10) { Break } |
||
Ins_Text(", ") |
Ins_Text(", ") |
||
} |
} |
||
Ins_Newline |
Ins_Newline |
||
</syntaxhighlight> |
|||
=={{header|Verilog}}== |
|||
<syntaxhighlight lang="Verilog"> |
|||
module main; |
|||
integer i; |
|||
initial begin |
|||
for(i = 1; i <= 10; i = i + 1) begin |
|||
$write(i); |
|||
if (i < 10 ) $write(", "); |
|||
end |
|||
$display(""); |
|||
$finish ; |
|||
end |
|||
endmodule |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
=={{header|Vim Script}}== |
=={{header|Vim Script}}== |
||
<syntaxhighlight lang="vim"> |
|||
<lang vim>for i in range(1, 10) |
|||
for i in range(1, 10) |
|||
echon i |
echon i |
||
if (i != 10) |
if (i != 10) |
||
echon ", " |
echon ", " |
||
endif |
endif |
||
endfor |
endfor |
||
</syntaxhighlight> |
|||
=={{header| |
=={{header|V (Vlang)}}== |
||
<syntaxhighlight lang="go"> |
|||
<lang vbnet>For i = 1 To 10 |
|||
fn main() { |
|||
Console.Write(i) |
|||
for i := 1; ; i++ { |
|||
print(i) |
|||
Console.Write(", ") |
|||
if i == 10 { |
|||
Next</lang> |
|||
break |
|||
} |
|||
print(", ") |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
<syntaxhighlight lang="wart"> |
|||
<lang wart>for i 1 (i <= 10) ++i |
|||
for i 1 (i <= 10) ++i |
|||
pr i |
pr i |
||
if (i < 10) |
if (i < 10) |
||
pr ", " |
pr ", " |
||
(prn) |
(prn) |
||
</syntaxhighlight> |
|||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren"> |
|||
for (i in 1..10) { |
|||
System.write(i) |
|||
System.write((i < 10) ? ", " : "\n") |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 |
|||
</pre> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
<syntaxhighlight lang="xpl0"> |
|||
<lang XPL0>codes CrLf=9, IntOut=11, Text=12; |
|||
codes CrLf=9, IntOut=11, Text=12; |
|||
int N; |
int N; |
||
[for N:= 1 to 10 do \best way to do this |
[for N:= 1 to 10 do \best way to do this |
||
Line 2,184: | Line 3,689: | ||
]; |
]; |
||
CrLf(0); |
CrLf(0); |
||
] |
|||
]</lang> |
|||
</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
<syntaxhighlight lang="zkl"> |
|||
<lang zkl>foreach n in ([1..10]){ print(n); if (n!=10) print(",") }</lang> |
|||
foreach n in ([1..10]){ print(n); if (n!=10) print(",") } |
|||
</syntaxhighlight> |
|||
Or, using a state machine: |
Or, using a state machine: |
||
<syntaxhighlight lang="zkl"> |
|||
<lang zkl>[1..10].pump(Console.print, Void.Drop, T(Void.Write,",",Void.Drop));</lang> |
|||
[1..10].pump(Console.print, Void.Drop, T(Void.Write,",",Void.Drop)); |
|||
</syntaxhighlight> |
|||
where pump is (sink, action, action ...). The first Drop writes the |
where pump is (sink, action, action ...). The first Drop writes the |
||
first object from the source (1) to the sink and drops out (and that |
first object from the source (1) to the sink and drops out (and that |
||
Line 2,195: | Line 3,705: | ||
collects things to write to the sink: a comma and the number, eg ",2". |
collects things to write to the sink: a comma and the number, eg ",2". |
||
Or: |
Or: |
||
<syntaxhighlight lang="zkl"> |
|||
<lang zkl>[1..10].pump(Console.print, Void.Drop, fcn(n){ String(",",n) });</lang> |
|||
[1..10].pump(Console.print, Void.Drop, fcn(n){ String(",",n) }); |
|||
</syntaxhighlight> |
|||
=={{header|Zig}}== |
|||
<syntaxhighlight lang="zig"> |
|||
const std = @import("std"); |
|||
pub fn main() !void { |
|||
const stdout_wr = std.io.getStdOut().writer(); |
|||
var i: u8 = 1; |
|||
while (i <= 10) : (i += 1) { |
|||
try stdout_wr.print("{d}", .{i}); |
|||
if (i == 10) { |
|||
try stdout_wr.writeAll("\n"); |
|||
} else { |
|||
try stdout_wr.writeAll(", "); |
|||
} |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{omit from|PL/0}} |
Latest revision as of 07:08, 8 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
Quite often one needs loops which, in the last iteration, execute only part of the loop body.
- Goal
Demonstrate the best way to do this.
- Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number and the comma from within the body of the loop.
- 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
11l
L(i) 1..10
print(i, end' ‘’)
I !L.last_iteration
print(‘, ’, end' ‘’)
360 Assembly
* Loops/N plus one half 13/08/2015
LOOPHALF CSECT USING LOOPHALF,R12
LR R12,R15
BEGIN LA R3,MVC
SR R5,R5
LA R6,1
LA R7,10
LOOPI BXH R5,R6,ELOOPI for i=1 to 10
XDECO R5,XDEC
MVC 0(4,R3),XDEC+8
LA R3,4(R3)
CH R5,=H'10'
BNL NEXTI
MVC 0(2,R3),=C', '
LA R3,2(R3)
NEXTI B LOOPI next i
ELOOPI XPRNT MVC,80
XR R15,R15
BR R14
MVC DC CL80' '
XDEC DS CL12
YREGS
END LOOPHALF
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
68000 Assembly
Sega Genesis cartridge header and hardware print routines/bitmap font are omitted here but do work as intended.
moveq #0,d0
move.w #1,d1 ;ABCD can't use an immediate operand
move.w #10-1,d2
loop:
abcd d1,d0
move.l d0,-(sp)
jsr printhex
move.l (sp)+,d0
cmp.b #$10,d0 ;we use hex 10 since this is binary-coded decimal
beq exitEarly
move.l d0,-(sp)
move.b #',',D0 ;PrintChar uses D0 as input
jsr PrintChar
move.b #' ',D0
jsr PrintChar
move.l (sp)+,d0
DBRA d2,loop
exitEarly:
; include "X:\SrcGEN\testModule.asm"
jmp *
- Output:
01, 02, 03, 04, 05, 06, 07, 08, 09, 10
8086 Assembly
Since the output of the last element is different than the rest, the easiest way to accomplish this is by "breaking out" of the loop with a comparison to 10.
.model small
.stack 1024
.data ;no data needed
.code
start:
mov ax,0000h
mov cx,0FFFFh ;this value doesn't matter as long as it's greater than decimal 10.
repeatPrinting:
add ax,1 ;it was easier to start at zero and add here than to start at 1 and add after printing.
aaa ;ascii adjust for addition, corrects 0009h+1 from 000Ah to 0100h
call PrintBCD_IgnoreLeadingZeroes
cmp ax,0100h ;does AX = BCD 10?
je exitLoopEarly ;if so, we're done now. Don't finish the loop.
push ax
mov dl,"," ;print a comma
mov ah,02h
int 21h
mov dl,20h ;print a blank space
mov ah,02h
int 21h
pop ax
loop repeatPrinting
exitLoopEarly:
mov ax,4C00h
int 21h ;return to DOS
PrintBCD_IgnoreLeadingZeroes:
push ax
cmp ah,0
jz skipLeadingZero
or ah,30h ;converts a binary-coded-decimal value to an ASCII numeral
push dx
push ax
mov al,ah
mov ah,0Eh
int 10h ;prints AL to screeen
pop ax
pop dx
skipLeadingZero:
or al,30h
push dx
push ax
mov ah,0Eh
int 10h ;prints AL to screen
pop ax
pop dx
pop ax
ret
end start ;EOF
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopnplusone64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "@" // message result
szMessComma: .asciz ", "
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x20,1 // loop counter
1: // begin loop
mov x0,x20
ldr x1,qAdrsZoneConv // display value
bl conversion10 // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv // display value
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrszMessComma
bl affichageMess // display comma
add x20,x20,1 // increment counter
cmp x20,10 // end ?
blt 1b // no ->begin loop one
mov x0,x20
ldr x1,qAdrsZoneConv // display value
bl conversion10 // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv // display value
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrszCarriageReturn
bl affichageMess // display return line
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
qAdrszMessComma: .quad szMessComma
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
ACL2
ACL2 does not have loops, but this is close:
(defun print-list (xs)
(progn$ (cw "~x0" (first xs))
(if (endp (rest xs))
(cw (coerce '(#\Newline) 'string))
(progn$ (cw ", ")
(print-list (rest xs))))))
Action!
PROC Main()
BYTE i=[1]
DO
PrintB(i)
IF i=10 THEN
EXIT
FI
Print(", ")
i==+1
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Ada
with Ada.Text_IO;
procedure LoopsAndHalf is
begin
for i in 1 .. 10 loop
Ada.Text_IO.put (i'Img);
exit when i = 10;
Ada.Text_IO.put (",");
end loop;
Ada.Text_IO.new_line;
end LoopsAndHalf;
Aime
integer i;
i = 0;
while (1) {
i += 1;
o_integer(i);
if (i == 10) {
break;
}
o_text(", ");
}
o_text("\n");
ALGOL 60
'BEGIN'
'COMMENT' Loops N plus one half - Algol60 - 20/06/2018;
'INTEGER' I;
'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO' 'BEGIN'
OUTINTEGER(1,I);
'IF' I 'NOTEQUAL' 10 'THEN' OUTSTRING(1,'(', ')')
'END'
'END'
- Output:
+1 , +2 , +3 , +4 , +5 , +6 , +7 , +8 , +9 , +10
ALGOL 68
There are three common ways of achieving n+½ loops:
FOR i WHILE
print(whole(i, -2));
# WHILE # i < 10 DO
print(", ")
OD;
print(new line) |
FOR i TO 10 DO
print(whole(i, -2));
IF i < 10 THEN
print(", ")
FI
OD;
print(new line) |
FOR i DO
print(whole(i, -2));
IF i >= 10 THEN GO TO done FI;
print(", ")
OD;
done:
print(new line) |
Output for all cases above:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
ALGOL W
begin
integer i;
i := 0;
while
begin
i := i + 1;
writeon( i );
i < 10
end
do
begin
writeon( "," )
end
end.
Amazing Hopper
Six ways to do this task in Hopper flavour "Jambo":
#include <jambo.h>
Main
i=1
Loop if ' Less equal (i,10)'
Set 'i', Print if ( #(i<10), ",","")
++i
Back
Prnl
Loop for ( i=1, #(i<=10), ++i )
Set 'i', Print only if ( #(10-i), ",")
Next
Prnl
i=1
Loop
Set 'i', Print only if ( #(10-i), ",")
++i
While ' #(i<=10) '
Prnl
i=1
Loop
Set 'i', Print only if ( #(10-i), ",")
++i
Until ' #(i>10) '
Prnl
i=1
Loop
Set 'i', and print it
Break if '#( !(10-i) )'
Set '","'
++i
Back
Prnl
/* assembler Hopper */
i=1
loop single:
{i,10,i} sub, do{{","}}, print
++i, {i,11}, jneq(loop single)
puts("\n")
End
- Output:
1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6,7,8,9,10
AmigaE
PROC main()
DEF i
FOR i := 1 TO 10
WriteF('\d', i)
EXIT i = 10
WriteF(', ')
ENDFOR
ENDPROC
ARM Assembly
/* ARM assembly Raspberry PI */
/* program loopnplusone.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .ascii "" @ message result
sMessValeur: .fill 11, 1, ' '
szMessComma: .asciz ","
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r4,#1 @ loop counter
1: @ begin loop
mov r0,r4
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ decimal conversion
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszMessComma
bl affichageMess @ display comma
add r4,#1 @ increment counter
cmp r4,#10 @ end ?
blt 1b @ no ->begin loop one
mov r0,r4
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ decimal conversion
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display return line
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
iAdrszMessComma: .int szMessComma
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
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"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
sub r2,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0
bne 1b @ else loop
@ end replaces digit in front of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4] @ store in area begin
add r4,#1
add r2,#1 @ previous position
cmp r2,#LGZONECAL @ end
ble 2b @ loop
mov r1,#0 @ final zero
strb r1,[r3,r4]
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} @ save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 @ r2 <- r2 >> 2
mov r1, r0, LSR #31 @ r1 <- r0 >> 31
add r0, r2, r1 @ r0 <- r2 + r1
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2-r4}
bx lr @ return
ArnoldC
IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE lessThanTen
YOU SET US UP @NO PROBLEMO
STICK AROUND lessThanTen
TALK TO THE HAND n
GET TO THE CHOPPER lessThanTen
HERE IS MY INVITATION 10
LET OFF SOME STEAM BENNET n
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE lessThanTen
TALK TO THE HAND ", "
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET UP @NO PROBLEMO
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED
Arturo
print join.with:", " map 1..10 => [to :string]
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Asymptote
for(int i = 1; i <= 10; ++i) {
write(i, suffix=none);
if(i < 10) write(", ", suffix=none);
}
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
AutoHotkey
Loop, 9 ; loop 9 times
{
output .= A_Index ; append the index of the current loop to the output var
If (A_Index <> 9) ; if it isn't the 9th iteration of the loop
output .= ", " ; append ", " to the output var
}
MsgBox, %output%
AutoIt
#cs ----------------------------------------------------------------------------
AutoIt Version: 3.3.8.1
Author: Alexander Alvonellos
Script Function:
Output a comma separated list from 1 to 10, and on the tenth iteration of the
output loop, only perform half of the loop.
#ce ----------------------------------------------------------------------------
Func doLoopIterative()
Dim $list = ""
For $i = 1 To 10 Step 1
$list = $list & $i
If($i = 10) Then ExitLoop
$list = $list & ", "
Next
return $list & @CRLF
EndFunc
Func main()
ConsoleWrite(doLoopIterative())
EndFunc
main()
AWK
One-liner:
$ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf ", "};print}'
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Readable version:
BEGIN {
n=10
for(i=1;i<=n;i++) {
printf i;
if(i<n) printf ", "
}
print
}
Same output.
Axe
For(I,1,10)
Disp I▶Dec
If I=10
Disp i
Else
Disp ","
End
End
BASIC
DIM i AS Integer
FOR i=1 TO 10
PRINT USING "##"; i;
IF i=10 THEN EXIT FOR
PRINT ", ";
NEXT i
Applesoft BASIC
The ZX Spectrum Basic code will work just fine in Applesoft BASIC. The following is a more structured approach which avoids the use of GOTO.
10 FOR I = 1 TO 10
20 PRINT I;
30 IF I < 10 THEN PRINT ", "; : NEXT I
ASIC
If equality checking affect the efficiency or if the last value were treated in different manner, one can extract the last iteration.
ASIC prints integer numbers as six-char strings. If shorter ones are needed, one can use the STR$
and LTRIM$
functions.
REM Loops/N plus one half
FOR I = 1 TO 9
PRINT I;
PRINT ",";
NEXT I
PRINT 10
END
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Basic09
PROCEDURE nAndAHalf
DIM i:INTEGER
FOR i:=1 TO 10
PRINT i;
EXITIF i=10 THEN ENDEXIT
PRINT ", ";
NEXT i
PRINT
BASIC256
for i = 1 to 10
print i;
if i < 10 then print ", ";
next i
end
BBC BASIC
FOR i% = 1 TO 10
PRINT ; i% ;
IF i% <> 10 PRINT ", ";
NEXT
PRINT
bootBASIC
There are no for/next or do/while loops in bootBASIC. Only goto.
10 a=1
20 print a ;
30 if a-10 goto 100
40 goto 130
100 print ", ";
110 a=a+1
120 goto 20
130 print
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Chipmunk Basic
10 rem Loops/N plus one half
20 c$ = ""
30 for i = 1 to 10
40 print c$;str$(i);
50 c$ = ", "
60 next i
FBSL
#APPTYPE CONSOLE
For Dim i = 1 To 10
PRINT i;
IF i < 10 THEN PRINT ", ";
Next
PAUSE
Output
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Press any key to continue...
FreeBASIC
' FB 1.05.0 Win64
For i As Integer = 1 To 10
Print Str(i);
If i < 10 Then Print ", ";
Next
Print
Sleep
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Alternative
This makes the important point that for many loops of this kind the partial iteration could easily be the first one.
dim as string cm = ""
for i as ubyte = 1 to 10
print cm;str(i);
cm = ", "
next i
FutureBasic
window 1
long i, num = 10
for i = 1 to num
print i;
if i = num then break
print @", ";
next i
HandleEvents
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Gambas
Click this link to run this code
Public Sub Main()
Dim siLoop As Short
For siLoop = 1 To 10
Print siLoop;
If siLoop <> 10 Then Print ", ";
Next
End
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
GW-BASIC
10 C$ = ""
20 FOR I = 1 TO 10
30 PRINT C$;STR$(I);
40 C$=", "
50 NEXT I
IS-BASIC
100 FOR I=1 TO 10
110 PRINT I;
120 IF I=10 THEN EXIT FOR
130 PRINT ",";
140 NEXT
Liberty BASIC
Keyword 'exit' allows the termination.
for i =1 to 10
print i;
if i =10 then exit for
print ", ";
next i
end
Microsoft Small Basic
For i = 1 To 10
TextWindow.Write(i)
If i <> 10 Then
TextWindow.Write(", ")
EndIf
EndFor
TextWindow.WriteLine("")
NS-HUBASIC
10 FOR I=1 TO 10
20 PRINT I;
30 IF I=10 THEN GOTO 50
40 PRINT ",";
50 NEXT
PureBasic
x=1
Repeat
Print(Str(x))
x+1
If x>10: Break: EndIf
Print(", ")
ForEver
QBasic
FOR i = 1 TO 10
PRINT USING "##"; i;
IF i=10 THEN EXIT FOR
PRINT ", ";
NEXT i
Run BASIC
FOR i = 1 TO 10
PRINT cma$;i;
cma$ = ", "
NEXT i
Sinclair ZX81 BASIC
The ZX Spectrum Basic program will work on the ZX81. Depending on the context, the programmer's intention may be clearer if we do it all with GOTO
s instead of a FOR
loop.
10 LET I=1
20 PRINT I;
30 IF I=10 THEN GOTO 70
40 PRINT ", ";
50 LET I=I+1
60 GOTO 20
TI-89 BASIC
There is no horizontal cursor position on the program IO screen, so we concatenate strings instead.
Local str
"" → str
For i,1,10
str & string(i) → str
If i < 10 Then
str & "," → str
EndIf
EndFor
Disp str
Tiny BASIC
Tiny BASIC does not support string concatenation so each number is on a separate line but this is at least in the spirit of the task description.
LET I = 1
10 IF I = 10 THEN PRINT I
IF I < 10 THEN PRINT I,", "
IF I = 10 THEN END
LET I = I + 1
GOTO 10
A solution for the dialects of Tiny BASIC that support string concatenation.
10 REM Loops/N plus one half
20 LET I = 1
30 IF I = 10 THEN PRINT I
40 IF I < 10 THEN PRINT I; ", ";
50 IF I = 10 THEN END
60 LET I = I + 1
70 GOTO 30
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
True BASIC
LET cm$ = ""
FOR i = 1 to 10
PRINT cm$; str$(i);
LET cm$ = ", "
NEXT i
END
VBA
Public Sub WriteACommaSeparatedList()
Dim i As Integer
Dim a(1 To 10) As String
For i = 1 To 10
a(i) = CStr(i)
Next i
Debug.Print Join(a, ", ")
End Sub
Visual Basic .NET
For i = 1 To 10
Console.Write(i)
If i = 10 Then Exit For
Console.Write(", ")
Next
Wee Basic
print 1 "" ensures the end of program text is separate from the list of numbers.
print 1 ""
for numbers=1 to 10
print 1 at numbers*3-2,0 numbers
if numbers<>10
print 1 at numbers*3-1,0 ","
endif
end
XBasic
PROGRAM "n_plus_one_half"
DECLARE FUNCTION Entry()
FUNCTION Entry()
FOR i% = 1 TO 10
PRINT i%;
IF i% = 10 THEN EXIT FOR
PRINT ",";
NEXT i%
END FUNCTION
END PROGRAM
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
If equality checking affect the efficiency or if the last value were treated in different manner, one can extract the last iteration.
PROGRAM "n_plus_one_half"
DECLARE FUNCTION Entry()
FUNCTION Entry()
FOR i% = 1 TO 9
PRINT i%; ",";
NEXT i%
PRINT 10
END FUNCTION
END PROGRAM
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Yabasic
for i = 1 to 10
print i;
if i < 10 print ", ";
next i
print
end
ZX Spectrum Basic
To terminate a loop on the ZX Spectrum, set the loop counter to a value that will exit the loop, before jumping to the NEXT statement.
10 FOR i=1 TO 10
20 PRINT i;
30 IF i=10 THEN GOTO 50
40 PRINT ", ";
50 NEXT i
bc
The print
extension is necessary to get the required output.
while (1) {
print ++i
if (i == 10) {
print "\n"
break
}
print ", "
}
Befunge
1+>::.9`#@_" ,",,
This code is a good answer. However, most Befunge implementations print a " " after using . (output number), so this program prints "1 , 2 , 3 ..." with extra spaces. A bypass for this is possible, by adding 48 and printing the ascii character, but does not work with 10::
1+>::68*+,8`#v_" ,",,
@,,,,", 10"<
Bracmat
1:?i
& whl
' ( put$!i
& !i+1:~>10:?i
& put$", "
)
C
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++) {
printf("%d", i);
printf(i == 10 ? "\n" : ", ");
}
return 0;
}
C#
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 1; ; i++)
{
Console.Write(i);
if (i == 10) break;
Console.Write(", ");
}
Console.WriteLine();
}
}
C++
#include <iostream>
int main()
{
int i;
for (i = 1; i<=10 ; i++){
std::cout << i;
if (i < 10)
std::cout << ", ";
}
return 0;
}
Chapel
for i in 1..10 do
write(i, if i % 10 > 0 then ", " else "\n")
Clojure
; Functional version
(apply str (interpose ", " (range 1 11)))
; Imperative version
(loop [n 1]
(printf "%d" n)
(if (< n 10)
(do
(print ", ")
(recur (inc n)))))
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. Loop-N-And-Half.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 I PIC 99.
01 List PIC X(45).
PROCEDURE DIVISION.
PERFORM FOREVER
*> The list to display must be built up because using
*> DISPLAY adds an endline at the end automatically.
STRING FUNCTION TRIM(List) " " I INTO List
IF I = 10
EXIT PERFORM
END-IF
STRING FUNCTION TRIM(List) "," INTO List
ADD 1 TO I
END-PERFORM
DISPLAY List
GOBACK
.
Free-form, 'List'-free version, using DISPLAY NO ADVANCING.
IDENTIFICATION DIVISION.
PROGRAM-ID. LOOP-1p5-NOADV.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 I PIC 99 VALUE 1.
01 IDISP PIC Z9.
PROCEDURE DIVISION.
PERFORM FOREVER
MOVE I TO IDISP
DISPLAY FUNCTION TRIM(IDISP) WITH NO ADVANCING
IF I = 10
EXIT PERFORM
END-IF
DISPLAY ", " WITH NO ADVANCING
ADD 1 TO I
END-PERFORM.
STOP RUN.
END-PROGRAM.
Free-form, GO TO, 88-level. Paragraphs in PROCEDURE DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. LOOP-1p5-NOADV-GOTO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 I PIC 99 VALUE 1.
88 END-LIST VALUE 10.
01 I-OUT PIC Z9.
PROCEDURE DIVISION.
01-LOOP.
MOVE I TO I-OUT.
DISPLAY FUNCTION TRIM(I-OUT) WITH NO ADVANCING.
IF END-LIST GO TO 02-DONE.
DISPLAY ", " WITH NO ADVANCING.
ADD 1 TO I.
GO TO 01-LOOP.
02-DONE.
STOP RUN.
END-PROGRAM.
Using 'PERFORM VARYING'
IDENTIFICATION DIVISION.
PROGRAM-ID. LOOP-1p5-NOADV-VARY.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 I PIC 99 VALUE 1.
88 END-LIST VALUE 10.
01 I-OUT PIC Z9.
PROCEDURE DIVISION.
PERFORM WITH TEST AFTER VARYING I FROM 1 BY 1 UNTIL END-LIST
MOVE I TO I-OUT
DISPLAY FUNCTION TRIM(I-OUT) WITH NO ADVANCING
IF NOT END-LIST
DISPLAY ", " WITH NO ADVANCING
END-IF
END-PERFORM.
STOP RUN.
END-PROGRAM.
CoffeeScript
# Loop plus half. This code shows how to break out of a loop early
# on the last iteration. For the contrived example, there are better
# ways to generate a comma-separated list, of course.
start = 1
end = 10
s = ''
for i in [start..end]
# the top half of the loop executes every time
s += i
break if i == end
# the bottom half of the loop is skipped for the last value
s += ', '
console.log s
ColdFusion
With tags:
<cfloop index = "i" from = "1" to = "10">
#i#
<cfif i EQ 10>
<cfbreak />
</cfif>
,
</cfloop>
With script:
<cfscript>
for( i = 1; i <= 10; i++ ) //note: the ++ notation works only on version 8 up, otherwise use i=i+1
{
writeOutput( i );
if( i == 10 )
{
break;
}
writeOutput( ", " );
}
</cfscript>
Common Lisp
(loop for i from 1 below 10 do
(princ i) (princ ", ")
finally (princ i))
or
(loop for i from 1 upto 10 do
(princ i)
(if (= i 10) (return))
(princ ", "))
but for such simple tasks we can use format's powers:
(format t "~{~a~^, ~}" (loop for i from 1 to 10 collect i))
Using DO
(do ((i 1 (incf i))) ; Initialize to 1 and increment on every loop
((> i 10)) ; Break condition
(princ i) ; Print the iteration number
(when (= i 10) (go end)) ; Use the implicit tagbody and go to end tag when reach the last iteration
(princ ", ") ; Printing the comma is jumped by the go statement
end) ; The tag
or
(do ; Not exactly separate statements for the number and the comma
((i 1 (incf i))) ; Initialize to 1 and increment on every loop
((> i 9) (princ i)) ; Break condition when iteration is the last number, print it
(princ i) ; Print number statement
(princ ", ")) ; Print comma statement
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Cowgol
include "cowgol.coh";
var i: uint8 := 1;
loop
print_i8(i);
if i == 10 then break; end if;
print(", ");
i := i + 1;
end loop;
print_nl();
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
D
Iterative
import std.stdio;
void main() {
for (int i = 1; ; i++) {
write(i);
if (i >= 10)
break;
write(", ");
}
writeln();
}
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Functional Style
void main() {
import std.stdio, std.range, std.algorithm, std.conv, std.string;
iota(1, 11).map!text.join(", ").writeln;
// A simpler solution:
writefln("%(%d, %)", iota(1, 11));
}
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Dart
String loopPlusHalf(start, end) {
var result = '';
for(int i = start; i <= end; i++) {
result += '$i';
if(i == end) {
break;
}
result += ', ';
}
return result;
}
void main() {
print(loopPlusHalf(1, 10));
}
Delphi
program LoopsNPlusOneHalf;
{$APPTYPE CONSOLE}
var
i: integer;
const
MAXVAL = 10;
begin
for i := 1 to MAXVAL do
begin
Write(i);
if i < MAXVAL then
Write(', ');
end;
Writeln;
end.
Draco
proc nonrec main() void:
byte i;
i := 1;
while
write(i);
i := i + 1;
i <= 10
do
write(", ")
od
corp
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
DWScript
var i : Integer;
for i := 1 to 10 do begin
Print(i);
if i < 10 then
Print(', ');
end;
E
A typical loop+break solution:
var i := 1
while (true) {
print(i)
if (i >= 10) { break }
print(", ")
i += 1
}
Using the loop primitive in a semi-functional style:
var i := 1
__loop(fn {
print(i)
if (i >= 10) {
false
} else {
print(", ")
i += 1
true
}
})
EasyLang
for i = 1 to 10
write i
if i < 10
write ", "
.
.
EchoLisp
(string-delimiter "")
(for ((i (in-range 1 11))) (write i) #:break (= i 10) (write ","))
→ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10
;; or
(string-join (range 1 11) ",")
→ 1,2,3,4,5,6,7,8,9,10
EDSAC order code
[ N and a half times loop
=======================
A program for the EDSAC
Works with Initial Orders 2 ]
T56K
GK
O16@
[ 1 ] T24@
A25@
A18@
U25@
S23@
E11@
O25@
O19@
O20@
G1@
[ 11 ] O18@
O17@
O21@
O22@
ZF
[ 16 ] #F
[ 17 ] PF
[ 18 ] QF
[ 19 ] NF
[ 20 ] !F
[ 21 ] @F
[ 22 ] &F
[ 23 ] JF
[ 24 ] PF
[ 25 ] PF
EZPF
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Alternative
In the original EDSAC solution, the last number is printed outside the loop. My understanding of the task is that all numbers should be printed inside the loop, and control should then pass out of the loop without printing a comma after the last number.
To avoid dragging in a number-printing subroutine just to print 10, the output from the subroutines below has been changed to the single digits 0..9.
The first subroutine sticks to the task description: "in the last iteration, execute only part of the loop body". Two conditional jumps are encountered each time round the loop. The second subroutine skips the first part of the first iteration. This may not exactly fit the task description, but it has the advantage of requiring only one conditional jump within the loop. Cf. the S-lang solution and the comment by its author.
[Loop-and-a-half for Rosetta Code.
EDSAC program, Initial Orders 2.]
T64K [load at location 64 (arbitrary choice)]
GK [set @ (theta) parameter]
[Constants]
[0] OF [digit 9]
[1] JF [to inc digit after subtracting 9]
[2] #F [figures mode]
[3] !F [space]
[4] NF [comma (in figures mode)]
[5] @F [carriage return]
[6] &F [line feed]
[Variable]
[7] PF [current digit]
[First subroutine to print digits 0..9]
[8] A3F T20@ [plant return link as usual]
T7@ [digit := 0]
[11] O7@ [loop: print digit]
A7@ S@ [is digit 9?]
E20@ [if so, jump to exit]
O4@ O3@ [print comma and space]
A1@ [inc digit in acc]
T7@ [update digit in store]
E11@ [always loop back]
[20] ZF [(planted) return to caller with acc = 0]
[Second subroutine to print digits 0..9
Instead of saying "print a comma after each digit except the last"
it says "print a comma before each digit except the first".]
[21] A3F T33@ [plant return link as usual]
T7@ [digit := 0]
E29@ [jump into middle of loop]
[25] A1@ [loop: inc digit in acc]
T7@ [update digit in store]
O4@ O3@ [print comma and space]
[29] O7@ [print digit]
A7@ S@ [is digit 9?]
G25@ [if not, loop back]
[33] ZF [(planted) return to caller with acc = 0]
[Enter with acc = 0]
[34] O2@ [set teleprinter to figures]
A35@ G8@ [call first subroutine]
O5@ O6@ [print CR, LF]
A39@ G21@ [call second subroutine]
O5@ O6@ [print CR, LF]
O2@ [print dummy character to flush teleprinter buffer]
ZF [stop]
E34Z [define entry point]
PF [value of acc on entry (here = 0)]
[end]
- Output:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Elixir
defmodule Loops do
def n_plus_one_half([]), do: IO.puts ""
def n_plus_one_half([x]), do: IO.puts x
def n_plus_one_half([h|t]) do
IO.write "#{h}, "
n_plus_one_half(t)
end
end
Enum.to_list(1..10) |> Loops.n_plus_one_half
EMal
int LAST_ITERATION = 10
for int i = 1; i <= LAST_ITERATION ; ++i
write(i)
if i == LAST_ITERATION do break end
write(", ")
end
writeLine()
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Erlang
%% Implemented by Arjun Sunel
-module(loop).
-export([main/0]).
main() ->
for_loop(1).
for_loop(N) ->
if N < 10 ->
io:format("~p, ",[N] ),
for_loop(N+1);
true ->
io:format("~p\n",[N])
end.
ERRE
FOR I=1 TO 10 DO
PRINT(I;)
EXIT IF I=10
PRINT(", ";)
END FOR
Euphoria
for i = 1 to 10 do
printf(1, "%g", {i})
if i < 10 then
puts(1, ", ")
end if
end for
While, yes, use of exit
would also work here, it is slightly faster to code it this way, if only the last iteration has something different.
F#
Functional version that works for lists of any length
let rec print (lst : int list) =
match lst with
| hd :: [] ->
printf "%i " hd
| hd :: tl ->
printf "%i, " hd
print tl
| [] -> printf "\n"
print [1..10]
Factor
: print-comma-list ( n -- )
[ [1,b] ] keep '[
[ number>string write ]
[ _ = [ ", " write ] unless ] bi
] each nl ;
Falcon
for value = 1 to 10
formiddle
>> value
>> ", "
end
forlast: > value
end
- Output:
prompt$ falcon forto.fal 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
FALSE
1[$9>~][$.", "1+]#.
Fantom
class Main
{
public static Void main ()
{
for (Int i := 1; i <= 10; i++)
{
Env.cur.out.writeObj (i)
if (i == 10) break
Env.cur.out.writeChars (", ")
}
Env.cur.out.printLine ("")
}
}
Forth
: comma-list ( n -- )
dup 1 ?do i 1 .r ." , " loop
. ;
: comma-list ( n -- )
dup 1+ 1 do
i 1 .r
dup i = if leave then \ or DROP UNLOOP EXIT to exit loop and the function
[char] , emit space
loop drop ;
: comma-list ( n -- )
1
begin dup 1 .r
2dup <>
while ." , " 1+
repeat 2drop ;
Fortran
C Loops N plus one half - Fortran IV (1964)
INTEGER I
WRITE(6,301) (I,I=1,10)
301 FORMAT((I3,','))
END
C WARNING: This program is not valid ANSI FORTRAN 77 code. It uses
C two nonstandard characters on the lines labelled 5001 and 5002.
C Many F77 compilers should be okay with it, but it is *not*
C standard.
PROGRAM LOOPPLUSONEHALF
INTEGER I, TEN
C I'm setting a parameter to distinguish from the label 10.
PARAMETER (TEN = 10)
DO 10 I = 1, TEN
C Write the number only.
WRITE (*,5001) I
C If we are on the last one, stop here. This will make this test
C every iteration, which can slow your program down a little. If
C you want to speed this up at the cost of your own convenience,
C you could loop only to nine, and handle ten on its own after
C the loop is finished. If you don't care, power to you.
IF (I .EQ. TEN) GOTO 10
C Append a comma to the number.
WRITE (*,5002) ','
10 CONTINUE
C Always finish with a newline. This programmer hates it when a
C program does not end its output with a newline.
WRITE (*,5000) ''
STOP
5000 FORMAT (A)
C Standard FORTRAN 77 is completely incapable of completing a
C WRITE statement without printing a newline. This program would
C be much more difficult (i.e. impossible) to write in the ANSI
C standard, without cheating and saying something like:
C
C WRITE (*,*) '1, 2, 3, 4, 5, 6, 7, 8, 9, 10'
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 (I3, $)
5002 FORMAT (A, $)
C5001 FORMAT (T3, ADVANCE='NO')
C5001 FORMAT (A, ADVANCE='NO')
END
i = 1
do
write(*, '(I0)', advance='no') i
if ( i == 10 ) exit
write(*, '(A)', advance='no') ', '
i = i + 1
end do
write(*,*)
GAP
n := 10;
for i in [1 .. n] do
Print(i);
if i < n then
Print(", ");
else
Print("\n");
fi;
od;
GML
str = ""
for(i = 1; i <= 10; i += 1)
{
str += string(i)
if(i != 10)
str += ", "
}
show_message(str)
Go
package main
import "fmt"
func main() {
for i := 1; ; i++ {
fmt.Print(i)
if i == 10 {
fmt.Println()
break
}
fmt.Print(", ")
}
}
Gosu
var out = System.out
for(i in 1..10) {
if(i > 1) out.print(", ")
out.print(i)
}
Groovy
Solution:
for(i in (1..10)) {
print i
if (i == 10) break
print ', '
}
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Haskell
main :: IO ()
main = forM_ [1 .. 10] $ \n -> do
putStr $ show n
putStr $ if n == 10 then "\n" else ", "
You can also use intersperse :: a -> [a] -> [a]
intercalate ", " (map show [1..10])
Haxe
for (i in 1...11)
Sys.print('$i${i == 10 ? '\n' : ', '}');
hexiscript
for let i 1; i <= 10; i++
print i
if i = 10; break; endif
print ", "
endfor
println ""
HicEst
DO i = 1, 10
WRITE(APPend) i
IF(i < 10) WRITE(APPend) ", "
ENDDO
HolyC
U8 i, max = 10;
for (i = 1; i <= max; i++) {
Print("%d", i);
if (i == max) break;
Print(", ");
}
Print("\n");
Icon and Unicon
The above can be written more succinctly as:
IDL
Nobody would ever use a loop in IDL to output a vector of numbers - the requisite output would be generated something like this:
print,indgen(10)+1,format='(10(i,:,","))'
However if a loop had to be used it could be done like this:
for i=1,10 do begin
print,i,format='($,i)'
if i lt 10 then print,",",format='($,a)'
endfor
(which merely suppresses the printing of the comma in the last iteration);
or like this:
for i=1,10 do begin
print,i,format='($,i)'
if i eq 10 then break
print,",",format='($,a)'
end
(which terminates the loop early if the last element is reached).
J
output=: verb define
buffer=: buffer,y
)
loopy=: verb define
buffer=: ''
for_n. 1+i.10 do.
output ":n
if. n<10 do.
output ', '
end.
end.
echo buffer
)
Example use:
loopy 0
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
That said, note that neither loops nor output statements are necessary:
;}.,(', ' ; ":)&> 1+i.10
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
And, note also that this sort of data driven approach can also deal with more complex issues:
commaAnd=: ":&.> ;@,. -@# {. (<;._1 '/ and /') ,~ (<', ') #~ #
commaAnd i.5
0, 1, 2, 3 and 4
Java
public static void main(String[] args) {
for (int i = 1; ; i++) {
System.out.print(i);
if (i == 10)
break;
System.out.print(", ");
}
System.out.println();
}
JavaScript
function loop_plus_half(start, end) {
var str = '',
i;
for (i = start; i <= end; i += 1) {
str += i;
if (i === end) {
break;
}
str += ', ';
}
return str;
}
alert(loop_plus_half(1, 10));
Alternatively, if we stand back for a moment from imperative assumptions about the nature and structure of computing tasks, it becomes clear that the problem of special transitional cases as a pattern terminates has no necessary connection with loops. (See the comments accompanying the ACL2, Haskell, IDL, J and R examples above and below, and see also some of the approaches taken in languages like Clojure and Scala.
If a JavaScript expression evaluates to an array [1 .. 10] of integers, for example, we can map that array directly to a comma-delimited string by using the Array.join() function, writing something like:
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(
function (x, i) {
return m + i;
}
);
}
console.log(
range(1, 10).join(', ')
);
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Otherwise, any special transitional case at the end of a pattern can be handled by defining conditional values for one or more sub-expressions:
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
return m + i;
});
}
console.log(
(function (nFrom, nTo) {
var iLast = nTo - 1;
return range(nFrom, nTo).reduce(
function (accumulator, n, i) {
return accumulator +
n.toString() +
(i < iLast ? ', ' : ''); // conditional sub-expression
}, ''
)
})(1, 10)
);
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Otherwise
var s=1, e=10
for (var i=s; i<=e; i+=1) {
document.write( i==s ? '' : ', ', i )
}
or
var s=1, e=10
for (;; s+=1) {
document.write( s )
if (s==e) break
document.write( ', ' )
}
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
jq
In jq, it is idiomatic to view a range of integers with boundaries m and n as [m, n), i.e. including m but excluding n.
One approach is to construct the answer incrementally:
def loop_plus_half(m;n):
if m<n then reduce range(m+1;n) as $i (m|tostring; . + ", " + ($i|tostring))
else empty
end;
# An alternative that is shorter and perhaps closer to the task description because it uses range(m;n) is as follows:
def loop_plus_half2(m;n):
[range(m;n) | if . == m then . else ", ", . end | tostring] | join("");
- Output:
loop_plus_half2(1;11) # "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"
Julia
The short-circuiting && is idiomatic to Julia - the second expression will only be evaluated if the first one is true.
for i = 1:10
print(i)
i == 10 && break
print(", ")
end
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
K
p:{`0:$x} / output
i:1;do[10;p[i];p[:[i<10;", "]];i+:1];p@"\n"
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Alternative solutions:
10 {p@x;p@:[x<10;", ";"\n"];x+1}\1;
{p@x;p@:[x<10;", ";"\n"];x+1}'1+!10; /variant
Kotlin
// version 1.0.6
fun main(args: Array<String>) {
for (i in 1 .. 10) {
print(i)
if (i < 10) print(", ")
}
}
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
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_N_plus_one_half
{lambda {:i :n}
{if {> :i :n}
then (end of loop with a dot)
else {if {= :i 6} then {br}:i else :i}{if {= :i :n} then . else ,}
{loops_N_plus_one_half {+ :i 1} :n}}}}
-> loops_N_plus_one_half
{loops_N_plus_one_half 0 10}
-> 0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10. (end of loop with a dot)
Lang
# Loop
$i = 1
loop {
fn.print($i)
if($i === 10) {
con.break
}
fn.print(\,\s)
$i += 1
}
fn.println()
# Array generate from and join
fn.println(fn.join(\,\s, fn.arrayGenerateFrom(fn.inc, 10)))
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Lang5
: , dup ", " 2 compress "" join ;
1 do dup 10 != if dup , . 1 + else . break then loop
Word: Loops/For#Lang5
: 2string 2 compress "" join ;
: , dup 10 != if ", " 2string then ;
1 10 "dup , . 1+" times
Lasso
local(out) = ''
loop(10) => {
#out->append(loop_count)
loop_count == 10 ? loop_abort
#out->append(', ')
}
#out
Lhogho
type
doesn't output a newline. The print
outputs one.
for "i [1 10]
[
type :i
if :i < 10
[
type "|, |
]
]
print
A more list-y way of doing it
to join :lst :sep
if list? :lst
[
ifelse count :lst > 1
[
op (word first :lst :sep joinWith butfirst :lst :sep)
]
[
op (word last :lst)
]
]
op :lst
end
make "aList [1 2 3 4 5 6 7 8 9 10]
print join :aList "|, |
Lisaac
Section Header
+ name := LOOP_AND_HALF;
Section Public
- main <- (
+ i : INTEGER;
i := 1;
{
i.print;
i = 10
}.until_do {
", ".print;
i := i + 1;
};
'\n'.print;
);
LiveCode
repeat with n = 1 to 10
put n after loopn
if n is not 10 then put comma after loopn
end repeat
put loopn
Logo
to comma.list :n
repeat :n-1 [type repcount type "|, |]
print :n
end
comma.list 10
Lua
Translation of C:
for i = 1, 10 do
io.write(i)
if i == 10 then break end
io.write", "
end
M2000 Interpreter
Module Checkit {
\\ old type loop
For i=1 to 10
Print i;
If i=10 Then Exit For
Print ", ";
Next i
Print
\\ fast type loop. Continue exit block, without breaking loop.
For i=1 to 10 {
Print i;
If i=10 Then Continue
Print ", ";
}
Print
Print
i=0
{
loop \\ this mark block for loop, each time need to mark
i++
Print i;
If i=10 Then Exit ' so now we use exit to break loop
Print ", ";
}
Print
}
Checkit
M4
define(`break',
`define(`ulim',llim)')
define(`for',
`ifelse($#,0,``$0'',
`define(`ulim',$3)`'define(`llim',$2)`'ifelse(ifelse($3,`',1,
`eval($2<=$3)'),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),ulim,`$4')')')')
for(`x',`1',`',
`x`'ifelse(x,10,`break',`, ')')
Make
NEXT=`expr $* + 1`
MAX=10
RES=1
all: 1-n;
$(MAX)-n:
@echo $(RES)
%-n:
@-make -f loop.mk $(NEXT)-n MAX=$(MAX) RES=$(RES),$(NEXT)
Invoking it
|make -f loop.mk MAX=10 1,2,3,4,5,6,7,8,9,10
Maple
> for i to 10 do printf( "%d%s", i, `if`( i = 10, "\n", ", " ) ) end:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Mathematica/Wolfram Language
i = 1; s = "";
While[True,
s = s <> ToString@i;
If[i == 10, Break[]];
s = s <> ",";
i++;
]
s
MATLAB / Octave
Vectorized form:
printf('%i, ',1:9); printf('%i\n',10);
Explicite loop:
for k=1:10,
printf('%i', k);
if k==10, break; end;
printf(', ');
end;
printf('\n');
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
MAXScript
for i in 1 to 10 do
(
format "%" i
if i == 10 then exit
format "%" ", "
)
Metafont
Since message append always a newline, we need building the output inside a string, and then we output it.
last := 10;
string s; s := "";
for i = 1 upto last:
s := s & decimal i;
if i <> last: s := s & ", " fi;
endfor
message s;
end
min
min's linrec
combinator is flexible enough to easily accomodate this task, due to taking a quotation to execute at the end of the loop (the second one).
1 (dup 10 ==) 'puts! (print succ ", " print!) () linrec
Modula-3
MODULE Loop EXPORTS Main;
IMPORT IO, Fmt;
VAR i := 1;
BEGIN
LOOP
IO.Put(Fmt.Int(i));
IF i = 10 THEN EXIT; END;
IO.Put(", ");
i := i + 1;
END;
IO.Put("\n");
END Loop.
MUMPS
LOOPHALF
NEW I
FOR I=1:1:10 DO
.WRITE I
.IF I'=10 WRITE ", "
QUIT
;Alternate
NEW I FOR I=1:1:10 WRITE I WRITE:I'=10 ", "
KILL I QUIT
Output:
USER>D LOOPHALF^ROSETTA 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 USER>D LOOPHALF+7^ROSETTA 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Nemerle
foreach (i in [1 .. 10])
{
Write(i);
unless (i == 10) Write(", ");
}
NetRexx
/* NetRexx */
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
say
say 'Loops/N plus one half'
rs = ''
istart = 1
iend = 10
loop i_ = istart to iend
rs = rs || ' ' || i_
if i_ < iend then do
rs = rs','
end
end i_
say rs.strip()
Output
Loops/N plus one half 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
NewLISP
(for (i 0 10)
(print i)
(unless (= i 10)
(print ", ")))
Nim
var s = ""
for i in 1..10:
s.add $i
if i == 10: break
s.add ", "
echo s
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Nu
for i in 1.. {
print -n $i
if $i == 10 {
print ""
break
}
print -n ", "
}
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Oberon-07
Using a FOR loop
Should also work with Oberon-2.
MODULE LoopsNPlusOneHalf1;
IMPORT Out;
VAR i :INTEGER;
BEGIN
FOR i := 1 TO 10 DO
Out.Int( i, 0 );
IF i < 10 THEN Out.String( ", " ) END
END
END LoopsNPlusOneHalf1.
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Using an extended WHILE loop
Whilst probably not the best way of handling the task, this example demonstrates the extended WHILE loop available in Oberon-07.
The WHILE loop can have multiple conditions and DO pats. The conditions following WHILE and ELSIF are evaluated in order and the DO part corresponding to the first TRUE one is executed.
The loop terminates when all the conditions evaluate to FALSE
MODULE LoopsNPlusOneHalf;
IMPORT Out;
VAR i :INTEGER;
BEGIN
i := 0;
WHILE i < 9 DO
i := i + 1;
Out.Int( i, 0 );
Out.String( ", " )
ELSIF i < 10 DO
i := i + 1;
Out.Int( i, 0 )
END
END LoopsNPlusOneHalf.
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Objeck
bundle Default {
class Hello {
function : Main(args : String[]) ~ Nil {
for(i := 1; true; i += 1;) {
i->Print();
if(i = 10) {
break;
};
", "->Print();
};
'\n'->Print();
}
}
}
OCaml
let last = 10 in
for i = 1 to last do
print_int i;
if i <> last then
print_string ", ";
done;
print_newline();
let ints = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] in
let str_ints = List.map string_of_int ints in
print_endline (String.concat ", " str_ints);
Oforth
: loopn
| i |
10 loop: i [ i dup print 10 ifEq: [ break ] "," . ] printcr ;
Oz
Using a for-loop:
for N in {List.number 1 10 1} break:Break do
{System.printInfo N}
if N == 10 then {Break} end
{System.printInfo ", "}
end
However, it seems more natural to use a left fold:
declare
fun {CommaSep Xs}
case Xs of nil then nil
[] X|Xr then
{FoldL Xr
fun {$ Z X} Z#", "#X end
X}
end
end
in
{System.showInfo {CommaSep {List.number 1 10 1}}}
Panda
Panda is stream based. To know if there is no more values you need to know it's the last. You can only do that if you get all the values. So this is functional style; We accumulate all the values from the stream. Then join them together as strings with a comma.
array{{1..10}}.join(',')
PARI/GP
n=0;
while(1,
print1(n++);
if(n>9, break);
print1(", ")
);
Pascal
program numlist(output);
const MAXNUM: integer = 10;
var
i: integer;
begin
{ loop 1: w/ if branching }
for i := 1 to MAXNUM do
begin
write(i);
if i <> MAXNUM then
write(', ')
end;
writeln;
{ loop 2: w/o if branching }
for i := 1 to MAXNUM-1 do
write(i, ', ');
writeln(MAXNUM);
end.
PascalABC.NET
##
for var i:=1 to 10 do
Write(i, i = 10 ? '' : ', ');
Peloton
<@ FORLITLIT>10|<@ SAYPOSFOR>...</@><@ ABF>,</@></@>
Perl
for my $i(1..10) {
print $i;
last if $i == 10;
print ', ';
}
print "\n";
In perl one would solve the task via join
.
print join(', ', 1..10), "\n";
Phix
for i=1 to 10 do printf(1,"%d",i) if i=10 then exit end if printf(1,", ") end for
Phixmonti
/# Rosetta Code problem: https://rosettacode.org/wiki/Loops/N_plus_one_half
by Galileo, 11/2022 #/
10 for dup print 10 == not if ", " print endif endfor
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 === Press any key to exit ===
PHP
for ($i = 1; $i <= 11; $i++) {
echo $i;
if ($i == 10)
break;
echo ', ';
}
echo "\n";
PicoLisp
(for N 10
(prin N)
(T (= N 10))
(prin ", ") )
Pike
int main(){
for(int i = 1; i <= 11; i++){
write(sprintf("%d",i));
if(i == 10){
break;
}
write(", ");
}
write("\n");
}
The most idiomatic way of inserting delimiters in Pike is the multiplication operator and it's symmetry with division of strings.
> "1, 2, 3"/", ";
Result: ({ "1", "2", "3" })
> ({ "1", "2", "3" })*", ";
Result: "1, 2, 3"
So achieving the result of this task with the method more suited to Pike would be:
array a = (array(string))enumerate(10, 1, 1);
write(a * ", " + "\n");
PL/I
do i = 1 to 10;
put edit (trim(i)) (a);
if i < 10 then put edit (', ') (a);
end;
Plain English
To run:
Start up.
Write the numbers up to 10 on the console.
Wait for the escape key.
Shut down.
To write the numbers up to a number on the console:
If a counter is past the number, exit.
Convert the counter to a string.
Write the string on the console without advancing.
If the counter is less than the number, write ", " on the console without advancing.
Repeat.
Pop11
lvars i;
for i from 1 to 10 do
printf(i, '%p');
quitif(i = 10);
printf(', ', '%p');
endfor;
printf('\n', '%p');
PowerShell
for ($i = 1; $i -le 10; $i++) {
Write-Host -NoNewLine $i
if ($i -eq 10) {
Write-Host
break
}
Write-Host -NoNewLine ", "
}
An interesting alternative solution, although not strictly a loop, even though switch
certainly loops over the given range.
switch (1..10) {
{ $true } { Write-Host -NoNewLine $_ }
{ $_ -lt 10 } { Write-Host -NoNewLine ", " }
{ $_ -eq 10 } { Write-Host }
}
Prolog
example :-
between(1,10,Val), write(Val), Val<10, write(', '), fail.
example.
?- example. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 true.
Python
The particular pattern and example chosen in the task description is recognised by the Python language and there are more idiomatic ways to achieve the result that don't even require an explicit conditional test such as:
print ( ', '.join(str(i+1) for i in range(10)) )
But the named pattern is shown by code such as the following:
>>> from sys import stdout
>>> write = stdout.write
>>> n, i = 10, 1
>>> while True:
write(i)
i += 1
if i > n:
break
write(', ')
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
>>>
List comprehension one-liner
[print(str(i+1) + ", ",end='') if i < 9 else print(i+1) for i in range(10)]
n, i = 10, 1
while True:
print(i, end="")
i += 1
if i > n:
break
print(", ", end="")
Quackery
10 times
[ i^ 1+ echo
i 0 = iff
conclude done
say ", " ]
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
R
The natural way to solve this task in R is:
paste(1:10, collapse=", ")
The task specifies that we should use a loop however, so this more verbose code is needed.
for(i in 1:10)
{
cat(i)
if(i==10)
{
cat("\n")
break
}
cat(", ")
}
Racket
#lang racket
(for ((i (in-range 1 15)))
(display i)
#:break (= 10 i)
(display ", "))
Gives the desired output.
Raku
(formerly Perl 6)
for 1 .. 10 {
.print;
last when 10;
print ', ';
}
print "\n";
REBOL
REBOL [
Title: "Loop Plus Half"
URL: http://rosettacode.org/wiki/Loop/n_plus_one_half
]
repeat i 10 [
prin i
if 10 = i [break]
prin ", "
]
print ""
Red
Red[]
repeat i 10 [
prin i
if 10 = i [break]
prin ", "
]
print ""
Relation
set i = 1
set result = ""
while i <= 10
set result = result . i
if i < 10
set result = result . ", "
end if
set i = i + 1
end while
echo result
REXX
two CHAROUTs
/*REXX program displays: 1,2,3,4,5,6,7,8,9,10 */
do j=1 to 10
call charout ,j /*write the DO loop index (no LF). */
if j<10 then call charout ,"," /*append a comma for one-digit numbers.*/
end /*j*/
/*stick a fork in it, we're all done. */
output
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
one CHAROUT
/*REXX program displays: 1,2,3,4,5,6,7,8,9,10 */
do j=1 for 10 /*using FOR is faster than TO. */
call charout ,j || left(',',j<10) /*display J, maybe append a comma (,).*/
end /*j*/
/*stick a fork in it, we're all done. */
output
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
version 3 if the number of items is not known
list='aa bb cc dd'
sep=', '
Do i=1 By 1 While list<>''
If i>1 Then Call charout ,sep
Parse Var list item list
Call charout ,item
End
- Output:
aa, bb, cc, dd
Ring
for x = 1 to 10 see x if x=10 exit ok see ", " next see nl
RPL
There are basically 2 possibilities, based on an overarching FOR..NEXT
or DO..UNTIL
/ WHILE..REPEAT
loop structure, in which an IF..THEN..ELSE
decides which parts of the loop must be executed. RPL does not have any instruction to just exit a loop.
The DO..UNTIL
/ WHILE..REPEAT
approach requires to use a flag and to manage a counter, which weighs down the code, as it can be seen in the implementations below.
≪ "" 1 10 FOR j j →STR + IF j 10 < THEN ", " + END NEXT ≫ 'S1→10' STO
17 words
≪ 1 CF "" 0 DO 1 + SWAP OVER →STR + IF OVER 10 < THEN ", " + ELSE 1 SF END SWAP UNTIL 1 FS? END DROP ≫ 'S1→10' STO
28 words + 1 flag
Ruby
(1..10).each do |i|
print i
break if i == 10
print ", "
end
puts
More idiomatic Ruby to obtain the same result is:
puts (1..10).join(", ")
Rust
fn main() {
for i in 1..=10 {
print!("{}{}", i, if i < 10 { ", " } else { "\n" });
}
}
More like the problem description:
fn main() {
for i in 1..=10 {
print!("{}", i);
if i == 10 {
break;
}
print!(", ");
}
println!();
}
Alternative solution using join
.
fn main() {
println!(
"{}",
(1..=10)
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(", ")
);
}
S-lang
This may constitute not following directions, but I've always felt the most readable and general way to code this is to move the "optional" part from the bottom to the top of the loop, then NOT include it on the FIRST pass:
variable more = 0, i;
foreach i ([1:10]) {
if (more) () = printf(", ");
printf("%d", i);
more = 1;
}
Salmon
iterate (x; [1...10])
{
print(x);
if (x == 10)
break;;
print(", ");
};
print("\n");
Scala
var i = 1
while ({
print(i)
i < 10
}) {
print(", ")
i += 1
}
println()
println((1 to 10).mkString(", "))
Scheme
It is possible to use continuations:
(call-with-current-continuation
(lambda (esc)
(do ((i 1 (+ 1 i))) (#f)
(display i)
(if (= i 10) (esc (newline)))
(display ", "))))
But usually making the tail recursion explicit is enough:
(let loop ((i 0))
(display i)
(if (= i 10)
(newline)
(begin
(display ", ")
(loop (+ 1 i)))))
Scilab
for i=1:10
printf("%2d ",i)
if i<10 then printf(", "); end
end
printf("\n")
- Output:
1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10
Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: number is 0;
begin
for number range 1 to 10 do
write(number);
if number < 10 then
write(", ")
end if;
end for;
writeln;
end func;
Sidef
for (1..10) { |i|
print i;
i == 10 && break;
print ', ';
}
print "\n";
Smalltalk
1 to: 10 do: [:n |
Transcript show: n asString.
n < 10 ifTrue: [ Transcript show: ', ' ]
]
Smalltalk/X and Pharo/Squeak have special enumeration messages for this in their Collection class, which executes another action in-between iterated elements:
(1 to: 10) do: [:n |
Transcript show: n asString.
] separatedBy:[
Transcript show: ', '
]
That is a bit different from the task's specification, but does what is needed here, and is more general in working with any collection (in the above case: a range aka "Interval"). It does not depend on the collection being addressed by an integer index and/or keeping a count inside the loop.
SNOBOL4
It's idiomatic in Snobol to accumulate the result in a string buffer for line output, and to use the same statement for loop control and the comma.
loop str = str lt(i,10) (i = i + 1) :f(out)
str = str ne(i,10) ',' :s(loop)
out output = str
end
For the task description, it's possible (implementation dependent) to set an output variable to raw mode for character output within the loop.
This example also breaks the loop explicitly:
output('out',1,'-[-r1]')
loop i = lt(i,10) i + 1 :f(end)
out = i
eq(i,10) :s(end)
out = ',' :(loop)
end
- Output:
1,2,3,4,5,6,7,8,9,10
SNUSP
@\>@\>@\>+++++++++<!/+. >-?\# digit and loop test
| | \@@@+@+++++# \>>.<.<</ comma and space
| \@@+@@+++++#
\@@@@=++++#
Spin
con
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
obj
ser : "FullDuplexSerial.spin"
pub main | n
ser.start(31, 30, 0, 115200)
repeat n from 1 to 10
ser.dec(n)
if n<10
ser.str(string(", "))
ser.str(string(13, 10))
waitcnt(_clkfreq + cnt)
ser.stop
cogstop(0)
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Stata
forv i=1/10 {
di `i' _continue
if `i'<10 {
di ", " _continue
}
else {
di
}
}
Mata
mata
for (i=1; i<=10; i++) {
printf("%f",i)
if (i<10) {
printf(", ")
} else {
printf("\n")
}
}
end
Swift
for var i = 1; ; i++ {
print(i)
if i == 10 {
println()
break
}
print(", ")
}
The usual way to do this with Swift 2 is:
for i in 1...10 {
print(i, terminator: i == 10 ? "\n" : ", ")
}
To satisfy the specification, we have to do something similar to Swift 1.x and other C-like languages:
for var i = 1; ; i++ {
print(i, terminator: "")
if i == 10 {
print("")
break
}
print(", ", terminator: "")
}
Tcl
for {set i 1; set end 10} true {incr i} {
puts -nonewline $i
if {$i >= $end} break
puts -nonewline ", "
}
puts ""
However, that's not how the specific task (printing 1..10 with comma separators) would normally be done. (Note, the solution below is not a solution to the half-looping problem.)
proc range {from to} {
set result {}
for {set i $from} {$i <= $to} {incr i} {
lappend result $i
}
return $i
}
puts [join [range 1 10] ", "] ;# ==> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
TUSCRIPT
$$ MODE TUSCRIPT
line=""
LOOP n=1,10
line=CONCAT (line,n)
IF (n!=10) line=CONCAT (line,", ")
ENDLOOP
PRINT line
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
UNIX Shell
for(( Z=1; Z<=10; Z++ )); do
echo -e "$Z\c"
if (( Z != 10 )); then
echo -e ", \c"
fi
done
for ((i=1;i<=$((last=10));i++)); do
echo -n $i
[ $i -eq $last ] && break
echo -n ", "
done
UnixPipes
The last iteration is handled automatically for us when there is no element in one of the pipes.
yes \ | cat -n | head -n 10 | paste -d\ - <(yes , | head -n 9) | xargs echo
Ursa
decl int i
for (set i 1) (< i 11) (inc i)
out i console
if (= i 10)
break
end if
out ", " console
end for
out endl console
V
[loop
[ [10 =] [puts]
[true] [dup put ',' put succ loop]
] when].
Using it
|1 loop =1,2,3,4,5,6,7,8,9,10
Vala
void main() {
for (int i = 1; i <= 10; i++)
{
stdout.printf("%d", i);
stdout.printf(i == 10 ? "\n" : ", ");
}
}
Vedit macro language
This example writes the output into current edit buffer.
for (#1 = 1; 1; #1++) {
Num_Ins(#1, LEFT+NOCR)
if (#1 == 10) { Break }
Ins_Text(", ")
}
Ins_Newline
Verilog
module main;
integer i;
initial begin
for(i = 1; i <= 10; i = i + 1) begin
$write(i);
if (i < 10 ) $write(", ");
end
$display("");
$finish ;
end
endmodule
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Vim Script
for i in range(1, 10)
echon i
if (i != 10)
echon ", "
endif
endfor
V (Vlang)
fn main() {
for i := 1; ; i++ {
print(i)
if i == 10 {
break
}
print(", ")
}
}
Wart
for i 1 (i <= 10) ++i
pr i
if (i < 10)
pr ", "
(prn)
Wren
for (i in 1..10) {
System.write(i)
System.write((i < 10) ? ", " : "\n")
}
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
XPL0
codes CrLf=9, IntOut=11, Text=12;
int N;
[for N:= 1 to 10 do \best way to do this
[IntOut(0, N); if N#10 then Text(0, ", ")];
CrLf(0);
N:= 1; \way suggested by task statement
loop [IntOut(0, N);
if N=10 then quit;
Text(0, ", ");
N:= N+1;
];
CrLf(0);
]
zkl
foreach n in ([1..10]){ print(n); if (n!=10) print(",") }
Or, using a state machine:
[1..10].pump(Console.print, Void.Drop, T(Void.Write,",",Void.Drop));
where pump is (sink, action, action ...). The first Drop writes the first object from the source (1) to the sink and drops out (and that iteration of the loop is done). For the rest of the loop, Write collects things to write to the sink: a comma and the number, eg ",2". Or:
[1..10].pump(Console.print, Void.Drop, fcn(n){ String(",",n) });
Zig
const std = @import("std");
pub fn main() !void {
const stdout_wr = std.io.getStdOut().writer();
var i: u8 = 1;
while (i <= 10) : (i += 1) {
try stdout_wr.print("{d}", .{i});
if (i == 10) {
try stdout_wr.writeAll("\n");
} else {
try stdout_wr.writeAll(", ");
}
}
}
- Programming Tasks
- Iteration
- Simple
- 11l
- 360 Assembly
- 68000 Assembly
- 8086 Assembly
- AArch64 Assembly
- ACL2
- Action!
- Ada
- Aime
- ALGOL 60
- ALGOL 68
- ALGOL W
- Amazing Hopper
- AmigaE
- ARM Assembly
- ArnoldC
- Arturo
- Asymptote
- AutoHotkey
- AutoIt
- AWK
- Axe
- BASIC
- Applesoft BASIC
- ASIC
- Basic09
- BASIC256
- BBC BASIC
- BootBASIC
- Chipmunk Basic
- FBSL
- FreeBASIC
- FutureBasic
- Gambas
- GW-BASIC
- IS-BASIC
- Liberty BASIC
- Microsoft Small Basic
- NS-HUBASIC
- PureBasic
- QBasic
- Run BASIC
- Sinclair ZX81 BASIC
- TI-89 BASIC
- Tiny BASIC
- True BASIC
- VBA
- Visual Basic .NET
- Wee Basic
- XBasic
- Yabasic
- ZX Spectrum Basic
- Bc
- Befunge
- Bracmat
- C
- C sharp
- C++
- Chapel
- Clojure
- COBOL
- CoffeeScript
- ColdFusion
- Common Lisp
- Cowgol
- D
- Dart
- Delphi
- Draco
- DWScript
- E
- EasyLang
- EchoLisp
- EDSAC order code
- Elixir
- EMal
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- Falcon
- FALSE
- Fantom
- Forth
- Fortran
- GAP
- GML
- Go
- Gosu
- Groovy
- Haskell
- Haxe
- Hexiscript
- HicEst
- HolyC
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Jq
- Julia
- K
- Kotlin
- LabVIEW
- Lambdatalk
- Lang
- Lang5
- Lasso
- Lhogho
- Lisaac
- LiveCode
- Logo
- Lua
- M2000 Interpreter
- M4
- Make
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- MAXScript
- Metafont
- Min
- Modula-3
- MUMPS
- Nemerle
- NetRexx
- NewLISP
- Nim
- Nu
- Oberon-07
- Objeck
- OCaml
- Oforth
- Oz
- Panda
- PARI/GP
- Pascal
- PascalABC.NET
- Peloton
- Perl
- Phix
- Phixmonti
- PHP
- PicoLisp
- Pike
- PL/I
- Plain English
- Pop11
- PowerShell
- Prolog
- Python
- Quackery
- R
- Racket
- Raku
- REBOL
- Red
- Relation
- REXX
- Ring
- RPL
- Ruby
- Rust
- S-lang
- Salmon
- Scala
- Scheme
- Scilab
- Seed7
- Sidef
- Smalltalk
- SNOBOL4
- SNUSP
- Spin
- Stata
- Swift
- Tcl
- TUSCRIPT
- UNIX Shell
- UnixPipes
- Ursa
- V
- Vala
- Vedit macro language
- Verilog
- Vim Script
- V (Vlang)
- Wart
- Wren
- XPL0
- Zkl
- Zig
- PL/0/Omit
- Pages with too many expensive parser function calls