Loops/Downward for

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

Write a for loop which writes a countdown from 10 to 0.

Contents

[edit] 6502 Assembly

Code is called as a subroutine (i.e. JSR Start). Printing routines are only partially coded here, specific OS/hardware routines for printing are left unimplemented.

;An OS/hardware specific routine that is setup to display the Ascii character
;value contained in the Accumulator
Send = $9000 ;routine not implemented here
PrintNewLine = $9050 ;routine not implemented here
 
*= $8000 ;set base address
Start PHA ;push Accumulator and Y register onto stack
TYA
PHA
LDY #10 ;set Y register to loop start value
TYA ;place loop value in the Accumulator
Loop JSR PrintTwoDigits
JSR PrintNewLine
DEY ;decrement loop value
BPL Loop ;continue loop if sign flag is clear
PLA ;pop Y register and Accumulator off of stack
TAY
PLA
RTS ;exit
 
;Print value in Accumulator as two hex digits
PrintTwoDigits
PHA
LSR
LSR
LSR
LSR
JSR PrintDigit
PLA
AND #$0F
JSR PrintDigit
RTS
 
;Convert value in Accumulator to an Ascii hex digit
PrintDigit
ORA #$30
JSR Send ;routine not implemented here
RTS

[edit] Ada

for I in reverse 0..10 loop
Put_Line(Integer'Image(I));
end loop;

[edit] ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
FOR i FROM 10 BY -1 TO 0 DO
print((i,new line))
OD

As a common extension the DOWNTO is sometimes included to optimise the loop termination logic. The DOWNTO is available in Marcel's ALGOL 68G and Cambridge ALGOL 68C.

FOR i FROM 10 DOWNTO 0 DO
print((i,new line))
OD

[edit] AmigaE

PROC main()
DEF i
FOR i := 10 TO 0 STEP -1
WriteF('\d\n', i)
ENDFOR
ENDPROC

[edit] AutoHotkey

x := 10
While (x >= 0)
{
output .= "`n" . x
x--
}
MsgBox % output
 

[edit] AWK

BEGIN {
for(i=10; i>=0; i--) {
print i
}
}

[edit] BASIC

FOR i = 10 TO 0 STEP -1
PRINT i
NEXT i

[edit] BBC BASIC

      FOR i% = 10 TO 0 STEP -1
PRINT i%
NEXT

[edit] bc

for (i = 10; i >= 0; i--) i
quit

[edit] Befunge

55+>:.:v
^ -1_@

[edit] Bracmat

  10:?i
& whl'(out$!i&!i+-1:~<0:?i)

[edit] Brat

10.to 0 { n | p n }

[edit] C

int i;
for(i = 10; i >= 0; --i)
printf("%d\n",i);

[edit] C++

for(int i = 10; i >= 0; --i)
std::cout << i << "\n";

[edit] C#

for (int i = 10; i >= 0; i--)
{
Console.WriteLine(i);
}

[edit] Clojure

(doseq [x (range 10 -1 -1)] (println x))

[edit] CoffeeScript

This could be written either in the array comprehension style, or in "regular" for loop style.

# The more compact "array comprehension" style
console.log i for i in [10..0]
 
# The "regular" for loop style.
for i in [10..0]
console.log i
 
# More compact version of the above
for i in [10..0] then console.log i
10
9
8
7
6
5
4
3
2
1
0

(the output is repeated three times; once for each loop)

[edit] ColdFusion

With tags:

<cfloop index = "i" from = "10" to = "0" step = "-1">
#i#
</cfloop>

With script:

<cfscript>
for( i = 10; i <= 0; i-- )
{
writeOutput( i );
}
</cfscript>

[edit] Common Lisp

(loop for i from 10 downto 1 do
(print i))

[edit] D

import std.stdio: writeln;
 
void main() {
for (int i = 10; i >= 0; --i)
writeln(i);
writeln();
 
foreach_reverse (i ; 0 .. 10 + 1)
writeln(i);
}
Output:
10
9
8
7
6
5
4
3
2
1
0

10
9
8
7
6
5
4
3
2
1
0

[edit] dc

does not use GNU extensions

[]s. is a comment

c clears the stack

[~...]p s. to print strings

l<register>x executes the macro

uses the macro f - [p] to print, this can be replaced by any complex expressions.

c
 
[macro s(swap) - (a b : b a)]s.
[Sa Sb La Lb] ss
 
[macro d(2dup) - (a b : a b a b)]s.
[Sa d Sb La d Lb lsx] sd
 
[macro m(for) - ]s.
[lfx 1 - ldx !<m ] sm
 
0 10 ldx [p] sf !<m
q

Using it

|dc < ./for.dc
10
9
...
0

[edit] Delphi

See Pascal

[edit] DWScript

for i := 10 downto 0 do
PrintLn(i);

[edit] E

for i in (0..10).descending() { println(i) }

[edit] EGL

for ( i int from 10 to 0 decrement by 1 )
SysLib.writeStdout( i );
end

[edit] Erlang

%% Implemented by Arjun Sunel
-module(downward_loop).
-export([main/0]).
 
main() ->
for_loop(10).
 
for_loop(N) ->
if N > 0 ->
io:format("~p~n",[N] ),
for_loop(N-1);
true ->
io:format("~p~n",[N])
end.
 
Output:
10
9
8
7
6
5
4
3
2
1
0
ok

[edit] Euphoria

for i = 10 to 0 by -1 do
? i
end for

[edit] Ela

[edit] Standard Approach

open console imperative
 
each writen [10,9..0]

Function 'each' is defined in imperative module as:

 
each f (x::xs) = f x $ each f xs
each _ [] = ()

[edit] Alternative Approach

open console
 
countDown m n | n < m = ()
| else = writen n $ countDown m (n-1)
 
countDown 0 10

[edit] Factor

11 iota <reversed> [ . ] each

[edit] FALSE

10[$0>][$." "1-]#.

[edit] Fantom

 
class DownwardFor
{
public static Void main ()
{
for (Int i := 10; i >= 0; i--)
{
echo (i)
}
}
}
 

[edit] Forth

Unlike the incrementing 10 0 DO-LOOP, this will print eleven numbers. The LOOP words detect crossing the floor of the end limit.

: loop-down  0 10 do  i .  -1 +loop ;

[edit] Fortran

Works with: Fortran version 90 and later
DO i = 10, 0, -1
WRITE(*, *) i
END DO
Works with: Fortran version 77 and later
      PROGRAM DOWNWARDFOR
C Initialize the loop parameters.
INTEGER I, START, FINISH, STEP
PARAMETER (START = 10, FINISH = 0, STEP = -1)
 
C If you were to leave off STEP, it would default to positive one.
DO 10 I = START, FINISH, STEP
WRITE (*,*) I
10 CONTINUE
 
STOP
END

[edit] F#

for i in 10..-1..0 do
printfn "%d" i

[edit] GML

for(i = 10; i >= 0; i += 1)
show_message(string(i))

[edit] Go

for i := 10; i >= 0; i-- {
fmt.Println(i)
}

[edit] Groovy

for (i in (10..0)) {
println i
}

[edit] Haskell

import Control.Monad
forM_ [10,9..0] print

[edit] HicEst

DO i = 10, 0, -1
WRITE() i
ENDDO

[edit] IDL

Using a loop (with an "increment of minus one" ):

for i=10,0,-1 do print,i

But in IDL one would rarely use loops (for anything) since practically everything can be done with vectors/arrays.

The "IDL way of doing things" for the countdown requested in the task would probably be this:

print,10-indgen(11)

[edit] Icon and Unicon

There are four looping controls 'every', 'repeat', 'until', and 'while' (see Introduction to Icon and Unicon/Looping Controls for more information.) The closest to a 'for' loop is 'every'.

every i := 10 to 0 by -1 do {
# things to do within the loop
}
 

[edit] Inform 6

for(i = 10: i >= 0: i--)
print i, "^";

[edit] J

J is array-oriented, so there is very little need for loops. For example, one could satisfy this task this way:

  ,. i. -11

J does support loops for those times they can't be avoided (just like many languages support gotos for those time they can't be avoided).

3 : 0 ] 11
for_i. i. - y do.
i 1!:2 ]2
end.
i.0 0
)

Though it's rare to see J code like this.

[edit] Java

for(i = 10; i >= 0; --i){
System.out.println(i);
}

[edit] JavaScript

for (var i=10; i>=0; --i) print(i);

[edit] Liberty BASIC

 
for i = 10 to 0 step -1
print i
next i
end
 

[edit] Lisaac

10.downto 0 do { i : INTEGER;
i.println;
 
};

[edit]

If the limit is less than the start, then FOR decrements the control variable. Otherwise, a fourth parameter could be given as a custom increment.

for [i 10 0] [print :i]

[edit] Lua

 
for i=10,0,-1 do
print(i)
end
 

[edit] M4

define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2 $3),1,
`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl
 
for(`x',`10',`>=0',`-1',`x
')

[edit] Maple

Using an explicit loop:

for i from 10 to 0 by -1 do print(i) end:

Pushing the loop into the kernel:

seq(print(i),i=10..0,-1)

[edit] Mathematica

Mathematica provides several ways to iterate over a range of numbers, small subtle differences are amongst them. 3 possible implementations are (exactly the same output):

Using For:

For[i = 10, i >= 0, i--, Print[i]]

Using Do:

Do[Print[i], {i, 10, 0, -1}]

Using Scan:

Scan[Print, Range[10, 0, -1]]

[edit] MATLAB / Octave

    for k = 10:-1:0,
printf('%d\n',k)
end;

A vectorized version of the code is

  printf('%d\n',10:-1:0);  

[edit] Maxima

for i from 10 thru 0 step -1 do print(i);

[edit] MAXScript

for i in 10 to 0 by -1 do print i

[edit] Mercury

:- module loops_downward_for.
:- interface.
 
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
:- import_module int.
 
main(!IO) :-
Print = (pred(I::in, !.IO::di, !:IO::uo) is det :-
io.write_int(I, !IO), io.nl(!IO)
),
int.fold_down(Print, 1, 10, !IO).

[edit] Metafont

for i = 10 step -1 until 0: show i; endfor
end

The basic set of macros for Metafont defines downto, so that we can write

for i = 10 downto 0: show i; endfor end

[edit] МК-61/52

1	0	П0	ИП0	L0	03	С/П

[edit] Modula-2

MODULE Downward;
IMPORT InOut;
 
VAR
i: INTEGER;
 
BEGIN
FOR i := 10 TO 0 BY -1 DO
InOut.WriteInt(i, 2);
InOut.WriteLn
END
END Downward.

[edit] Modula-3

FOR i := 10 TO 0 BY -1 DO
IO.PutInt(i);
END;

[edit] MUMPS

LOOPDOWN
NEW I FOR I=10:-1:1 WRITE I WRITE:I'=1 ", "
KILL I QUIT


[edit] Nemerle

for (i = 10; i >= 0; i--) {WriteLine($"$i")}
foreach (i in [10, 9 .. 0]) {WriteLine($"$i")}

[edit] NetRexx

/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
say
say 'Loops/Downward for'
 
loop i_ = 10 to 0 by -1
say i_.right(2)
end i_
 

[edit] Oberon-2

FOR i := 10 TO 0 BY -1 DO
Out.Int(i,0);
END;

[edit] Objeck

 
for(i := 10; i >= 0; i -= 1;) {
i->PrintLine();
};
 

[edit] OCaml

for i = 10 downto 0 do
Printf.printf "%d\n" i
done

[edit] Octave

for i = 10:-1:0
% ...
endfor

[edit] Oz

for I in 10..0;~1 do
{Show I}
end

[edit] PARI/GP

forstep(n=10,0,-1,print(n))

[edit] Pascal

for i := 10 downto 0 do
writeln(i);

[edit] Perl

foreach (reverse 0..10) {
print "$_\n";
}

[edit] Perl 6

Works with: Rakudo Star version 2010.08
for 10 ... 0 {
.say;
}

[edit] PHP

for ($i = 10; $i >= 0; $i--)
echo "$i\n";

or

foreach (range(10, 0) as $i)
echo "$i\n";

[edit] PicoLisp

(for (I 10 (ge0 I) (dec I))
(println I) )

or:

(mapc println (range 10 0))

[edit] Pike

int main(){
for(int i = 10; i >= 0; i--){
write(i + "\n");
}
}

[edit] PL/I

 
do i = 10 to 0 by -1;
put skip list (i);
end;
 

[edit] Pop11

lvars i;
for i from 10 by -1 to 0 do
printf(i, '%p\n');
endfor;

[edit] PowerShell

for ($i = 10; $i -ge 0; $i--) {
$i
}

Alternatively, the range operator might be used as well which simply returns a contiguous range of integers:

10..0

[edit] PureBasic

For i=10 To 0 Step -1
Debug i
Next

[edit] Python

for i in xrange(10, -1, -1):
print i

[edit] R

for(i in 10:0) {print(i)}

[edit] Racket

 
#lang racket
 
(for ([i (in-range 10 -1 -1)])
(displayln i))
 

[edit] REBOL

for i 10 0 -1 [print i]

[edit] Retro

11 [ putn space ] iterd

[edit] REXX

[edit] version 1

(equivalent to version 2 and version 3)

  do j=10  to 0  by -1
say j
end

[edit] version 2

(equivalent to version 1 and version 3)

  do j=10  by -1  to 0
say j
end

[edit] version 3

(equivalent to version 1 and version 2)

Anybody who programs like this should be hunted down and shot like dogs!

Hurrumph! Hurrumph!

  do j=10  by -2  to 0
say j
j=j+1 /*this increments the DO index. Do NOT program like this! */
end

[edit] version 4

This example isn't compliant to the task, but it shows that the increment/decrement can be a non-integer

  do j=30  to 1  by -.25
say j
end

[edit] Ruby

10.downto(0) do |i|
puts i
end

[edit] Salmon

for (x; 10; x >= 0; -1)
x!;

[edit] Sather

class MAIN is
main is
i:INT;
loop i := 10.downto!(0);
#OUT + i + "\n";
end;
end;
end;

[edit] Scala

for(i <- 10 to 0 by -1) println(i)
//or
10 to 0 by -1 foreach println

[edit] Scheme

(do ((i 10 (- i 1)))
((< i 0))
(display i)
(newline))

[edit] Seed7

for i range 10 downto 0 do
writeln(i);
end for;

[edit] Slate

10 downTo: 1 do: [| :n | print: n]

[edit] Smalltalk

10 to: 1 by: -1 do:[:aNumber | 
aNumber display.
Character space display.
]

[edit] SNUSP

++++++++++>++++++++++!/- @!\=@\.@@@-@-----#   atoi
\n counter #\?>.</ \ @@@+@+++++# itoa
loop

[edit] Tcl

for {set i 10} {$i >= 0} {incr i -1} {
puts $i
}
# puts "We have liftoff!"

[edit] TI-83 BASIC

 
:For(I,10,0,–1)
 :Disp I
:End
 

[edit] TI-89 BASIC

Local i
For i, 10, 0, –1
Disp i
EndFor

[edit] Trith

10 inc iota reverse [print] each
10 [dup print dec] [dup 0 >=] while drop

[edit] TUSCRIPT

 
$$ MODE TUSCRIPT
LOOP n=10,0,-1
PRINT n
ENDLOOP
 

[edit] UnixPipes

Works with: OpenBSD version 4.9
yes '' | cat -n | head -n 11 | while read n; do
expr $n - 1
done | tail -r

This pipe uses several nonstandard commands: cat -n and tail -r might not work with some systems. If there is no tail -r, try tac.

[edit] UNIX Shell

Works with: Bourne Shell
i=10
while test $i -ge 0; do
echo $i
i=`expr $i - 1`
done

Works with: bash
for(( Z=10; Z>=0; Z-- )); do
echo $Z
done

Works with: Bourne Shell
Library: jot
for i in `jot - 10 0 -1`; do
echo $i
done
Works with: Bourne Shell
for i in `seq 10 -1 0`; do
echo $i
done
 
# or better yet
seq 10 -1 0
 

[edit] V

10 
[0 >]
[dup puts pred]
while

[edit] Vedit macro language

for (#1 = 10; #1 >= 0; #1--) {
Num_Type(#1)
}

[edit] Visual Basic .NET

For i = 10 To 0 Step -1
Console.WriteLine(i)
Next

[edit] XPL0

include c:\cxpl\codes;          \intrinsic 'code' declarations
int I;
for I:= 10 downto 0 do
[IntOut(0, I); CrLf(0)]

[edit] ZX Spectrum Basic

10 FOR l = 10 TO 0 STEP -1
20 PRINT l
30 NEXT l
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox