Loops/N plus one half
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. The goal of this task is to demonstrate the best way to do this.
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.
See also: Loop/Break
[edit] 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))))))
[edit] Ada
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
procedure Loop_And_Half is
I : Positive := 1;
begin
loop
Put(Item => I, Width => 1);
exit when I = 10;
Put(", ");
I := I + 1;
end loop;
New_Line;
end Loop_And_Half;
[edit] ALGOL 68
There are three common ways of achieving n+½ loops:
FOR i WHILE |
FOR i TO 10 DO |
FOR i DO |
Output for all cases above:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
[edit] AmigaE
PROC main()
DEF i
FOR i := 1 TO 10
WriteF('\d', i)
EXIT i = 10
WriteF(', ')
ENDFOR
ENDPROC
[edit] 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%
[edit] 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()
[edit] AWK
$ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf ", "};print}'
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
[edit] BASIC
DIM i AS INTEGER
FOR i=1 TO 10
PRINT i;
IF i=10 THEN EXIT FOR
PRINT ", ";
NEXT i
[edit] 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
[edit] BBC BASIC
FOR i% = 1 TO 10
PRINT ; i% ;
IF i% <> 10 PRINT ", ";
NEXT
[edit] 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 unnecessary extra spaces. A bypass for this is possible, yet slightly less sane:
"0" v
1+>::"9"`#v_," ,",,>
>"01",,@
[edit] C
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++) {
printf("%d", i);
printf(i == 10 ? "\n" : ", ");
}
return 0;
}
[edit] C++
#include <iostream>
int main()
{
for (int i = 1; ; i++)
{
std::cout << i;
if (i == 10)
break;
std::cout << ", ";
}
std::cout << std::endl;
return 0;
}
[edit] 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();
}
}
[edit] 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)))))
[edit] 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>
[edit] 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
[edit] 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))
[edit] D
[edit] 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
[edit] Functional Style
Same output.
import std.stdio, std.range, std.algorithm, std.conv, std.string;
void main() {
iota(1, 11).map!text().join(", ").writeln();
}
[edit] 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.
[edit] DWScript
var i : Integer;
for i := 1 to 10 do begin
Print(i);
if i < 10 then
Print(', ');
end;
[edit] 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
}
})
[edit] 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.
[edit] 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.
[edit] 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]
[edit] Factor
: print-comma-list ( n -- )
[ [1,b] ] keep '[
[ number>string write ]
[ _ = [ ", " write ] unless ] bi
] each nl ;
[edit] FALSE
1[$9>~][$.", "1+]#.
[edit] 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 ("")
}
}
[edit] 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 ;
[edit] Fortran
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(*,*)
[edit] GML
str = ""
for(i = 1; i <= 10; i += 1)
{
str += string(i)
if(i != 10)
str += ", "
}
show_message(str)
[edit] Go
package main
import "fmt"
func main() {
for i := 1; ; i++ {
fmt.Print(i)
if i == 10 {
fmt.Println("")
break
}
fmt.Print(", ")
}
}
[edit] 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
[edit] Haskell
loop :: IO ()
loop = mapM_ action [1 .. 10]
where action n = do
putStr $ show n
putStr $ if n == 10 then "\n" else ", "
It is, however, arguable whether mapM_ counts as a loop.
[edit] HicEst
DO i = 1, 10
WRITE(APPend) i
IF(i < 10) WRITE(APPend) ", "
ENDDO
[edit] 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).
[edit] Icon and Unicon
procedure main()
every writes(i := 1 to 10) do
if i = 10 then break write()
else writes(", ")
end
The above can be written more succinctly as:
every writes(c := "",1 to 10) do c := ","
[edit] 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.
smoutput 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
[edit] 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();
}
[edit] 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));
[edit] 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
[edit] LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
[edit] 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
[edit] Liberty BASIC
Keyword 'exit' allows the termination.
for i =1 to 10
print i;
if i =10 then exit for
print ", ";
next i
end
[edit] 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;
);
[edit] Logo
to comma.list :n
repeat :n-1 [type repcount type "|, |]
print :n
end
comma.list 10
[edit] Lua
Translation of C:
for i = 1, 10 do
io.write(i)
if i == 10 then break end
io.write", "
end
[edit] 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',`, ')')
[edit] Mathematica
i = 1; s = "";
While[True,
s = s <> ToString@i;
If[i == 10, Break[]];
s = s <> ",";
i++;
]
s
[edit] 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
[edit] MAXScript
for i in 1 to 10 do
(
format "%" i
if i == 10 then exit
format "%" ", "
)
[edit] 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
[edit] 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
[edit] 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.
[edit] Nemerle
foreach (i in [1 .. 10])
{
Write(i);
unless (i == 10) Write(", ");
}
[edit] MUMPS
LOOPHALFOutput:
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
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
[edit] 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_.right(3)
if i_ < iend then do
rs = rs','
end
end i_
say rs
[edit] 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();
}
}
}
[edit] 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);
[edit] 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}}}
[edit] PARI/GP
n=0;
while(1,
print1(n++);
if(n>9, break);
print1(", ")
);
[edit] Pascal
program numlist(output);
var
i: integer;
begin
for i := 1 to 10 do
begin
write(i);
if i <> 10 then
write(', ')
end;
writeln;
end.
[edit] Perl
foreach my $i (1..10) {
print $i;
last if $i == 10;
print ', ';
}
print "\n";
[edit] Perl 6
for 1 .. 10 {
.print;
last when 10;
print ', ';
}
print "\n";
[edit] PHP
for ($i = 1; $i <= 11; $i++) {
echo $i;
if ($i == 10)
break;
echo ', ';
}
echo "\n";
[edit] PicoLisp
(for N 10
(prin N)
(T (= N 10))
(prin ", ") )
[edit] Pike
int main(){
for(int i = 1; i <= 11; i++){
write(sprintf("%d",i));
if(i == 10){
break;
}
write(", ");
}
write("\n");
}
[edit] PL/I
do i = 1 to 10;
put edit (trim(i)) (a);
if i < 10 then put edit (', ') (a);
end;
[edit] Pop11
lvars i;
for i from 1 to 10 do
printf(i, '%p');
quitif(i = 10);
printf(', ', '%p');
endfor;
printf('\n', '%p');
[edit] 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 }
}
[edit] PureBasic
x=1
Repeat
Print(Str(x))
x+1
If x>10: Break: EndIf
Print(", ")
ForEver
[edit] 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
>>>
[edit] 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(", ")
}
[edit] Racket
#lang racket
(for ((i (in-range 1 15)))
(display i)
#:break (= 10 i)
(display ", "))
Gives the desired output.
[edit] REBOL
rebol [
Title: "Loop Plus Half"
Date: 2009-12-16
Author: oofoe
URL: http://rosettacode.org/wiki/Loop/n_plus_one_half
]
repeat i 10 [
prin i
if 10 = i [break]
prin ", "
]
print ""
[edit] REXX
[edit] two CHAROUTs
/*REXX program to display: 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 1-digit nums*/
end /*j*/
/*stick a fork in it, we're done.*/
output
1,2,3,4,5,6,7,8,9,10
[edit] one CHAROUT
/*REXX program to display: 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) /*show J, maybe append a comma.*/
end /*j*/
/*stick a fork in it, we're done.*/
output
1,2,3,4,5,6,7,8,9,10
[edit] Ruby
for i in 1..10 do
print i
break if i == 10
print ", "
end
puts
[edit] Salmon
iterate (x; [1...10])
{
print(x);
if (x == 10)
break;;
print(", ");
};
print("\n");
[edit] 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)))))
[edit] 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;
[edit] 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
[edit] SNUSP
@\>@\>@\>+++++++++<!/+. >-?\# digit and loop test
| | \@@@+@+++++# \>>.<.<</ comma and space
| \@@+@@+++++#
\@@@@=++++#
[edit] 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
[edit] 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
[edit] 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
[edit] 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
[edit] 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
[edit] 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
[edit] 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
[edit] Visual Basic .NET
For i = 1 To 10
Console.Write(i)
If i = 10 Then Exit For
Console.Write(", ")
Next
[edit] 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);
]
- Programming Tasks
- Iteration
- ACL2
- Ada
- ALGOL 68
- AmigaE
- AutoHotkey
- AutoIT
- AWK
- BASIC
- ZX Spectrum Basic
- BBC BASIC
- Befunge
- C
- C++
- C sharp
- Clojure
- ColdFusion
- CoffeeScript
- Common Lisp
- D
- Delphi
- DWScript
- E
- Erlang
- Euphoria
- F Sharp
- Factor
- FALSE
- Fantom
- Forth
- Fortran
- GML
- Go
- Groovy
- Haskell
- HicEst
- IDL
- Icon
- Unicon
- J
- Java
- JavaScript
- K
- LabVIEW
- Lang5
- Liberty BASIC
- Lisaac
- Logo
- Lua
- M4
- Mathematica
- MATLAB
- Octave
- MAXScript
- Make
- Metafont
- Modula-3
- Nemerle
- MUMPS
- NetRexx
- Objeck
- OCaml
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- Pop11
- PowerShell
- PureBasic
- Python
- R
- Racket
- REBOL
- REXX
- Ruby
- Salmon
- Scheme
- Seed7
- SNOBOL4
- SNUSP
- Tcl
- TI-89 BASIC
- TUSCRIPT
- UnixPipes
- UNIX Shell
- V
- Vedit macro language
- Visual Basic .NET
- XPL0