Loops/While
Start an integer value at 1024. Loop while it is greater than 0. Print the value (with a newline) and divide it by two each time through the loop.
You are encouraged to solve this task according to the task description, using any language you may know.
0815
<lang 0815><:400:~}:_:%<:a:~$=<:2:=/^:_:</lang>
360 Assembly
Using binary arithmetic. Convert results to EBCDIC printable output. <lang 360 Assembly> WHILE CSECT , This program's control section
BAKR 14,0 Caller's registers to linkage stack LR 12,15 load entry point address into Reg 12 LA 13,0 inidicate caller no savearea USING WHILE,12 tell assembler we use Reg 12 as base XR 3,3 Register 3 zero. XR 4,4 clear even divident reg LA 5,1024 load odd divident reg LA 9,2 divisor in reg 9 LA 8,WTOLEN address of WTO area in Reg 8 MVC WTOTXT,=C'1024' WTO TEXT=(8) write to operator initial value 1024
LOOP DS 0H
DR 4,9 divide r4/5 by r9 CLR 3,4 less than zero? BL RETURN yes, return CVD 5,PACKED convert result to (packed) decimal OI PACKED+7,X'0F' prepare unpack XC WTOTXT,WTOTXT clear wto text UNPK WTOTXT,PACKED packed decimal to zoned (printable) WTO TEXT=(8) and write-to-operator B LOOP loop.
RETURN PR , return to caller. WTOLEN DC H'4' fixed WTO length of four WTOTXT DS CL4 PACKED DS CL8
END WHILE
</lang>
- Output:
(+ sign indicates "problem state" (non system key) issued WTO's
+1024 +0512 +0256 +0128 +0064 +0032 +0016 +0008 +0004 +0002 +0001
6502 Assembly
Code is called as a subroutine (i.e. JSR LoopsWhile). Specific OS/hardware routines for printing are left unimplemented. <lang 6502asm>LoopsWhile: PHA ;push accumulator onto stack
LDA #$00 ;the 6502 is an 8-bit processor STA Ilow ;and so 1024 ($0400) must be stored in two memory locations LDA #$04 STA Ihigh WhileLoop: LDA Ilow BNE NotZero LDA Ihigh BEQ EndLoop NotZero: JSR PrintI ;routine not implemented LSR Ihigh ;shift right ROR Ilow ;rotate right JMP WhileLoop
EndLoop: PLA ;restore accumulator from stack RTS ;return from subroutine</lang>
ActionScript
<lang actionscript>var i:int = 1024; while (i > 0) {
trace(i); i /= 2;
}</lang>
Ada
<lang ada>declare
I : Integer := 1024;
begin
while I > 0 loop Put_Line(Integer'Image(I)); I := I / 2; end loop;
end;</lang>
Aime
<lang aime>integer i;
i = 1024; while (i) {
o_plan(i, "\n"); i /= 2;
}</lang>
ALGOL 60
<lang algol60>INTEGER I; I:=1024; WHILE I>0 DO BEGIN
OUTINT(I); I:=I/2
END</lang>
ALGOL 68
<lang algol68>INT i := 1024; WHILE i > 0 DO
print(i); i := i OVER 2
OD</lang>
- Output:
+1024 +512 +256 +128 +64 +32 +16 +8 +4 +2 +1
ALGOL W
<lang algolw>begin
integer i; i := 1024; while i > 0 do begin write( i ); i := i div 2 end
end.</lang>
AmbientTalk
Note: in AmbientTalk, while:do: is a keyworded message (as in Smalltalk). Both arguments to this message must be blocks (aka anonymous functions or thunks).
<lang ambienttalk>// print 1024 512 etc def i := 1024; while: { i > 0 } do: {
system.print(" "+i); i := i/2;
}</lang>
AmigaE
<lang amigae>PROC main()
DEF i = 1024 WHILE i > 0 WriteF('\d\n', i) i := i / 2 ENDWHILE
ENDPROC</lang>
AppleScript
AppleScript does not natively support a standard out. Use the Script Editor's Event Log as the output. <lang AppleScript >set i to 1024 repeat while i > 0 log i set i to i / 2 end repeat</lang>
Applesoft BASIC
<lang Applesoft BASIC> 10 I% = 1024
20 IF I% > 0 THEN PRINT I%:I% = I% / 2: GOTO 20</lang>
AutoHotkey
<lang AutoHotkey>i = 1024 While (i > 0) {
output = %output%`n%i% i := Floor(i / 2)
} MsgBox % output</lang>
AWK
<lang awk>BEGIN {
v = 1024 while(v > 0) { print v v = int(v/2) }
}</lang>
Axe
<lang axe>1024→A While A>0
Disp A▶Dec,i A/2→A
End</lang>
BASIC
<lang qbasic>i = 1024 while i > 0
print i i = i / 2
wend</lang>
BBC BASIC
<lang bbcbasic> i% = 1024
WHILE i% PRINT i% i% DIV= 2 ENDWHILE</lang>
bc
<lang bc>i = 1024 while (i > 0) {
i i /= 2
}</lang>
Befunge
<lang befunge>84*:*> :v
^/2,*25.:_@</lang>
Bracmat
<lang bracmat>1024:?n & whl'(!n:>0 & out$!n & div$(!n.2):?n)</lang>
Brat
Converts to integers so output is a little bit shorter and neater.
<lang brat>i = 1024 while { i > 0 } {
p i i = (i / 2).to_i
}</lang>
C
<lang c>int i = 1024; while(i > 0) {
printf("%d\n", i); i /= 2;
}</lang> In for loop fashion: <lang c>int i; for(i = 1024;i > 0; i/=2){
printf("%d\n", i);
}</lang>
ChucK
<lang> 1024 => int value;
while(value > 0) {
<<<value>>>; value / 2 => value;
} </lang>
C++
<lang cpp>int i = 1024; while(i > 0) {
std::cout << i << std::endl; i /= 2;
}</lang>
Alternatively, it can be done with for
:
<lang cpp>for (int i = 1024; i>0; i /= 2)
std::cout << i << std::endl;</lang>
Indeed, in C++, <lang cpp>for (init; cond; update)
statement;</lang>
is equivalent to <lang cpp>{
init; while (cond) { statement; update; }
}</lang>
C#
<lang csharp>int i = 1024; while(i > 0){
System.Console.WriteLine(i); i /= 2;
}</lang>
Chapel
<lang chapel>var val = 1024; while val > 0 {
writeln(val); val /= 2;
}</lang>
Clojure
<lang lisp>(def i (ref 1024))
(while (> @i 0)
(println @i) (dosync (ref-set i (quot @i 2))))</lang>
2 ways without mutability:
<lang Clojure>(loop [i 1024]
(when (pos? i) (println i) (recur (quot i 2))))
(doseq [i (take-while pos? (iterate #(quot % 2) 1024))]
(println i))</lang>
COBOL
COBOL does not have a while loop construct, but it is does have a PERFORM UNTIL
structure, which means that the normal condition used in a while loop must be negated.
<lang cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. Loop-While.
DATA DIVISION. WORKING-STORAGE SECTION. 01 I PIC 9999 VALUE 1024.
PROCEDURE DIVISION. PERFORM UNTIL NOT 0 < I DISPLAY I DIVIDE 2 INTO I END-PERFORM
GOBACK .</lang>
ColdFusion
Remove the leading space from the line break tag.
With tags: <lang cfm><cfset i = 1024 /><cfloop condition="i GT 0"> #i#< br />
<cfset i /= 2 />
</cfloop></lang> With script: <lang cfm><cfscript> i = 1024;
while( i > 0 ) { writeOutput( i + "< br/ >" ); }
</cfscript></lang>
Common Lisp
<lang lisp>(setq i 1024) (loop while (> i 0) do
(print i) (setq i (floor i 2)))</lang>
Crack
<lang crack>i = 1024; while( i > 0 ) {
cout ` $i\n`; i = i/2;
}</lang>
Creative Basic
<lang Creative Basic>DEF X:INT
X=1024
OPENCONSOLE
WHILE X>0
PRINT X X=X/2
ENDWHILE 'Output starts with 1024 and ends with 1.
'Putting the following in the loop will produce output starting with 512 and ending with 0: 'X=X/2 'PRINT X
PRINT:PRINT"Press any key to end."
'Keep console from closing right away so the figures can be read. WHILE INKEY$="":ENDWHILE
CLOSECONSOLE
'Since this is, in fact, a Creative Basic console program. END</lang> Note: Spacing is not an issue. I just find the code to be more readable with spaces.
D
<lang d>import std.stdio;
void main() {
int i = 1024;
while (i > 0) { writeln(i); i >>= 1; }
}</lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
Dc
People may think all loops in Dc looks alike. In fact, there aren't loop, but conditional execution in Dc. You expand and execute the content of a register (in here, p) whenever the condition is satisfied. <lang Dc>1024[p2/d0<p]dspx</lang>
Dao
<lang dao>i = 1024; while( i > 0 ) i = i / 2;</lang>
Delphi
<lang Delphi>var
i : Integer;
begin
i := 1024;
while i > 0 do begin Writeln(i); i := i div 2; end;
end;</lang>
DWScript
<lang Delphi>var i := 1024;
while i > 0 do begin
PrintLn(i); i := i div 2;
end;</lang>
E
<lang e>var i := 1024 while (i > 0) {
println(i) i //= 2
}</lang>
EchoLisp
<lang lisp> (set! n 1024) (while (> n 0) (write n) (set! n (quotient n 2))) 1024 512 256 128 64 32 16 8 4 2 1 </lang>
EGL
<lang EGL>x int = 1024; while ( x > 0 )
SysLib.writeStdout( x ); x = MathLib.floor( x / 2 );
end</lang>
Elena
<lang elena>#import system.
- symbol program =
[
#var(type:int)i := 1024. #loop (i > 0)? [ console writeLine:i. i := i / 2. ].
].</lang>
Elixir
<lang elixir>defmodule Loops do
def while(0), do: :ok def while(n) do IO.puts n while( div(n,2) ) end
end
Loops.while(1024)</lang>
Emacs Lisp
<lang Lisp>(let ((i 1024))
(while (> i 0) (message "%d" i) (setq i (/ i 2))))</lang>
Erlang
<lang erlang>-module(while). -export([loop/0]).
loop() -> loop(1024).
loop(N) when N div 2 =:= 0 -> io:format("~w~n", [N]);
loop(N) when N >0 -> io:format("~w~n", [N]), loop(N div 2).</lang>
ERRE
<lang ERRE>
I%=1024 WHILE I%>0 DO ! you can leave out >0 PRINT(I%) I%=I% DIV 2 ! I%=INT(I%/2) for C-64 version END WHILE
</lang>
Euphoria
<lang Euphoria>integer i i = 1024
while i > 0 do
printf(1, "%g\n", {i}) i = floor(i/2) --Euphoria does NOT use integer division. 1/2 = 0.5
end while</lang>
Even without the floor()
the code will in fact end. But it's FAR beyond 1.
F#
<lang fsharp>let rec loop n = if n > 0 then printf "%d " n; loop (n / 2) loop 1024</lang>
Factor
<lang factor>1024 [ dup 0 > ] [ dup . 2 /i ] while drop</lang>
FALSE
<lang false>1024[$0>][$." "2/]#%</lang>
Fantom
<lang fantom>class Main {
public static Void main () { Int i := 1024 while (i > 0) { echo (i) i /= 2 } }
}</lang>
Forth
<lang forth>: halving ( n -- )
begin dup 0 > while cr dup . 2/ repeat drop ;
1024 halving</lang>
Fortran
<lang fortran>INTEGER :: i = 1024 DO WHILE (i > 0)
WRITE(*,*) i i = i / 2
END DO</lang>
<lang fortran> PROGRAM LOOPWHILE
INTEGER I
C FORTRAN 77 does not have a while loop, so we use GOTO statements C with conditions instead. This is one of two easy ways to do it.
I = 1024 10 CONTINUE
C Check condition.
IF (I .GT. 0) THEN
C Handle I.
WRITE (*,*) I I = I / 2
C Jump back to before the IF block.
GOTO 10 ENDIF STOP END</lang>
<lang fortran> PROGRAM LOOPWHILE
INTEGER I
C FORTRAN 66 does not have IF block.
I = 1024 10 CONTINUE IF (I .LE. 0) GOTO 20 WRITE (*,*) I I = I / 2 GOTO 10 20 CONTINUE STOP END</lang>
Frink
<lang frink>i=1024 while i>0 {
i = i/1
}</lang>
GAP
<lang gap>n := 1024; while n > 0 do
Print(n, "\n"); n := QuoInt(n, 2);
od;</lang>
GML
<lang GML>i = 1024 while(i > 0)
{ show_message(string(i)) i /= 2 }</lang>
Go
<lang go>i := 1024 for i > 0 {
fmt.Printf("%d\n", i) i /= 2
}</lang>
Groovy
Solution: <lang groovy>int i = 1024 while (i > 0) {
println i i /= 2
}</lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
Haskell
<lang haskell>import Control.Monad (when) main = loop 1024
where loop n = when (n > 0) (do print n loop (n `div` 2))</lang>
You could try to write a "while" that operates on monads:
<lang haskell>import Control.Monad (when)
whileM :: (Monad m) => m Bool -> m a -> m () whileM cond body = do c <- cond
when c (body >> whileM cond body)</lang>
You can use it like this
<lang haskell>import Data.IORef
main :: IO () main = do r <- newIORef 1024
whileM (do n <- readIORef r return (n > 0)) (do n <- readIORef r print n modifyIORef r (`div` 2))</lang>
Icon and Unicon
<lang icon>procedure main()
local i i := 1024 while write(0 < (i := i / 2))
end</lang>
Inform 7
<lang inform7>let N be 1024; while N > 0: say "[N][line break]"; let N be N / 2;</lang>
IWBASIC
<lang IWBASIC> DEF X:INT
X=1024
OPENCONSOLE
WHILE X>0
PRINT X X=X/2
ENDWHILE 'Output starts with 1024 and ends with 1.
'Putting the following in the loop will produce output starting with 512 and ending with 0: 'X=X/2 'PRINT X
'When compiled as a console only program, a press any key to continue message is automatic. 'I presume code is added by the compiler. CLOSECONSOLE
'Since this is, in fact, an IWBASIC console program, which compiles and runs. END</lang> Note: Spacing is not an issue. I just find the code to be more readable with spaces.
J
J is array-oriented, so there is very little need for loops. For example, one could satisfy this task this way:
<lang j>,. <.@-:^:*^:a: 1024</lang>
J does support loops for those times they can't be avoided (just like many languages support gotos for those time they can't be avoided).
<lang j>monad define 1024
while. 0 < y do. smoutput y y =. <. -: y end. i.0 0
)</lang>
Note: this defines an anonymous function (monad define, and the subsequent lines) and passes it the argument 1024, which means it will be executed as soon as the full definition is available.
Java
<lang java5>int i = 1024; while(i > 0){
System.out.println(i); i >>= 1; //also acceptable: i /= 2;
}</lang> With a for loop: <lang java5>for(int i = 1024; i > 0;i /= 2 /*or i>>= 1*/){
System.out.println(i);
}</lang>
JavaScript
<lang javascript>var n = 1024; while (n > 0) {
print(n); n /= 2;
}</lang>
In a functional idiom of JavaScript, however, we can not use a While statement to achieve this task, as statements return no value, mutate state, and can not be composed within other functional expressions.
Instead, we can define a composable loopWhile() function which has no side effects, and takes 3 arguments:
- An initial value
- A function which returns some derived value, corresponding to the body of the While loop
- A conditional function, corresponding to the While test
<lang JavaScript>function loopWhile(varValue, fnDelta, fnTest) {
'use strict'; var d = fnDelta(varValue);
return fnTest(d) ? [d].concat( loopWhile(d, fnDelta, fnTest) ) : [];
}
console.log(
loopWhile( 1024, function (x) { return Math.floor(x/2); }, function (x) { return x > 0; } ).join('\n')
);</lang>
If we assume integer division here (Math.floor(x/2)) rather than the floating point division (x/2) used in the imperative example, we obtain the output:
<lang JavaScript>512 256 128 64 32 16 8 4 2 1</lang>
Joy
<lang joy>DEFINE putln == put '\n putch.
1024 [] [dup putln 2 /] while.</lang>
jq
Using recurse/1<lang jq># To avoid printing 0, test if the input is greater than 1 1024 | recurse( if . > 1 then ./2 | floor else empty end)</lang> Using recurse/2 (requires jq >1.4) <lang jq>1024 | recurse( ./2 | floor; . > 0)</lang> Using a filter <lang jq>def task: if . > 0 then ., (./2 | floor | task) else empty end; 1024|task</lang> Using while/2
If your jq does not include while/2 as a builtin, here is its definition:
<lang jq>def while(cond; update): def _while: if cond then ., (update | _while) else empty end; _while;</lang>
For example: <lang jq>1024|while(. > 0; ./2|floor)</lang>
Julia
<lang Julia> n = 1024
while n > 0
println(n) n >>= 1
end </lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
LabVIEW
Use Round Towards -Inf to prevent the integer becoming a float.
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.
Lang5
<lang lang5>: /i / int ; : 0= 0 == ;
- dip swap '_ set execute _ ; : dupd 'dup dip ;
- 2dip swap '_x set swap '_y set execute _y _x ;
- while
do dupd 'execute 2dip rot 0= if break else dup 2dip then loop ;
1024 "dup 0 >" "dup . 2 /i" while</lang>
Lasso
<lang Lasso>local(i = 1024) while(#i > 0) => {^ #i + '\r' #i /= 2 ^}</lang>
Liberty BASIC
All integers are changed to floats if an operation creates a non-integer result. Without using int() the program keeps going until erroring because accuracy was lost. <lang lb>i = 1024 while i > 0
print i i = int( i / 2)
wend end</lang>
Lisaac
<lang Lisaac>+ i : INTEGER; i := 1024; { i > 0 }.while_do {
i.println; i := i / 2;
};</lang>
LiveCode
<lang LiveCode>put 1024 into n repeat while n > 0
put n & cr divide n by 2
end repeat</lang>
Logo
<lang logo>make "n 1024 while [:n > 0] [print :n make "n :n / 2]</lang>
LOLCODE
LOLCODE's loop semantics require an afterthought if a condition is used, thus the nop in the following example. The more idiomatic approach would have been to GTFO of the loop once n had reached 0.
<lang LOLCODE>HAI 1.3
I HAS A n ITZ 1024
IM IN YR loop UPPIN YR nop WILE n
VISIBLE n n R QUOSHUNT OF n AN 2
IM OUTTA YR loop
KTHXBYE</lang>
Lua
<lang lua>n = 1024 while n>0 do
print(n) n = math.floor(n/2)
end</lang>
Maple
To avoid generating an infinite sequence (1/2, 1/4, 1/8, 1/16, etc.) of fractions after n takes the value 1, we use integer division (iquo) rather than the solidus operation (/). <lang Maple>> n := 1024: while n > 0 do print(n); n := iquo(n,2) end:
1024 512 256 128 64 32 16 8 4 2 1</lang>
Mathematica
Mathematica does not support integer-rounding, it would result in getting fractions: 1/2, 1/4 , 1/8 and so on; the loop would take infinite time without using the Floor function: <lang Mathematica>i = 1024; While[i > 0,
Print[i]; i = Floor[i/2];
]</lang>
MATLAB / Octave
In Matlab (like Octave) the math is done floating point, then rounding to integer, so that 1/2 will be always 1 and never 0. A 'floor' is used to round the number. <lang Matlab>i = 1024; while (i > 0)
disp(i); i = floor(i/2);
end</lang>
A vectorized version of the code is
<lang Matlab> printf('%d\n', 2.^[log2(1024):-1:0]);</lang>
Maxima
<lang maxima>block([n], n: 1024, while n > 0 do (print(n), n: quotient(n, 2)));
/* using a C-like loop: divide control variable by two instead of incrementing it */ for n: 1024 next quotient(n, 2) while n > 0 do print(n);</lang>
MAXScript
<lang maxscript>a = 1024 while a > 0 do (
print a a /= 2
)</lang>
Make
<lang make>NEXT=`expr $* / 2` MAX=10
all: $(MAX)-n;
0-n:;
%-n: %-echo
@-make -f while.mk $(NEXT)-n MAX=$(MAX)
%-echo:
@echo $*</lang>
Invoking it <lang make>|make -f while.mk MAX=1024</lang>
Metafont
Metafont has no while loop, but it can be "simulated" easily.
<lang metafont>a := 1024; forever: exitif not (a > 0);
show a; a := a div 2;
endfor</lang>
MIRC Scripting Language
<lang mirc>alias while_loop {
var %n = 10 while (%n >= 0) { echo -a Countdown: %n dec %n }
}</lang>
МК-61/52
<lang>1 0 2 4 П0 ИП0 /-/ x<0 15 ИП0 2 / П0 БП 05 С/П</lang>
MIXAL
<lang MIXAL>
- X = M / N WHILE X > 0
- STORE EACH X IN NUMERIC ARRAY
- PRINT ARRAY
M EQU 1024 N EQU 2 LPR EQU 18 BUF0 EQU 100 MSG EQU 2000 LENGTH EQU 500 ORIG 3000 START IOC 0(LPR) ENTX M CALC STX BUF0,1 DIV =N= SRAX 5 INC1 1 JXP CALC ST1 LENGTH PRINT LDA BUF0,2 CHAR STX MSG OUT MSG(LPR) INC2 1 CMP2 LENGTH JNE PRINT HLT END START </lang>
Modula-2
<lang modula2>MODULE DivBy2;
IMPORT InOut;
VAR i: INTEGER;
BEGIN
i := 1024; WHILE i > 0 DO InOut.WriteInt(i, 4); InOut.WriteLn; i := i DIV 2 END
END DivBy2.</lang>
Modula-3
The usual module code and imports are omitted. <lang modula3>PROCEDURE DivBy2() =
VAR i: INTEGER := 1024; BEGIN WHILE i > 0 DO IO.PutInt(i); IO.Put("\n"); i := i DIV 2; END; END DivBy2;</lang>
Monte
<lang Monte> var i := 1024 while (i > 0):
traceln(i) i //= 2
</lang>
MOO
<lang moo>i = 1024; while (i > 0)
player:tell(i); i /= 2;
endwhile</lang>
Morfa
<lang morfa> import morfa.io.print;
var i = 1024; while(i > 0) {
println(i); i /= 2;
} </lang>
Nemerle
<lang Nemerle>mutable x = 1024; while (x > 0) {
WriteLine($"$x"); x /= 2;
}</lang> Or, with immutable types, after Haskell: <lang Nemerle>// within another function, eg Main() def loop(n : int) : void {
when (n > 0) { WriteLine($"$n"); loop(n / 2); }
}
loop(1024)</lang>
Neko
<lang Neko> var i = 1024
while(i > 0) {
$print(i + "\n"); i = $idiv(i, 2)
} </lang>
NetRexx
<lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols nobinary
say say 'Loops/While'
x_ = 1024 loop while x_ > 0 say x_.right(6) x_ = x_ % 2 -- integer division end</lang>
NewLISP
<lang NewLISP>(let (i 1024)
(while (> i 0) (println i) (setq i (/ i 2))))</lang>
Nim
<lang nim>var n: int = 1024 while n > 0:
echo(n) n = n div 2</lang>
Oberon-2
The usual module code and imports are ommited. <lang oberon2>PROCEDURE DivBy2*();
VAR i: INTEGER;
BEGIN
i := 1024; WHILE i > 0 DO Out.Int(i,0); Out.Ln; i := i DIV 2; END;
END DivBy2;</lang>
Objeck
<lang objeck>i := 1024; while(i > 0) {
i->PrintLine(); i /= 2;
};</lang>
OCaml
<lang ocaml>let n = ref 1024;; while !n > 0 do
Printf.printf "%d\n" !n; n := !n / 2
done;;</lang>
But it is more common to write it in a tail-recursive functional style: <lang ocaml>let rec loop n =
if n > 0 then begin Printf.printf "%d\n" n; loop (n / 2) end
in loop 1024</lang>
Octave
<lang octave>i = 1024; while (i > 0)
disp(i) i = floor(i/2);
endwhile</lang>
The usage of the type int32 is not convenient, since the math is done floating point, then rounding to integer, so that 1/2 will be always 1 and never 0.
Oforth
<lang Oforth>1024 while (dup 0 <>) [ dup println 2 / ]</lang>
OOC
<lang ooc> main: func {
value := 1024 while (value > 0) { value toString() println() value /= 2 }
} </lang>
Oz
Oz' for-loop can be used in a C-like manner: <lang oz>for I in 1024; I>0; I div 2 do
{Show I}
end</lang>
Alternatively, we can use the while
feature of the for-loop with a mutable variable:
<lang oz>declare
I = {NewCell 1024}
in
for while:@I > 0 do {Show @I} I := @I div 2 end</lang>
Panoramic
<lang Panoramic>dim x%:rem an integer
x%=1024
while x%>0
print x% x%=x%/2
end_while
rem output starts with 1024 and ends with 1.
terminate</lang>
PARI/GP
<lang parigp>n=1024; while(n,
print(n); n/=2
);</lang>
Panda
Panda doesn't have explicit loops, instead we solve it by using the transitive closure operator. It applies a function to each successive value, each unique value is outputted. Our function halves, we make sure that the result is greater than 0 and add newline. <lang panda>fun half(a) type integer->integer a.divide(2) 1024.trans(func:half).gt(0) nl </lang>
Pascal
<lang pascal>program divby2(output);
var
i: integer;
begin
i := 1024; while i > 0 do begin writeln(i); i := i div 2 end
end.</lang>
PeopleCode
<lang PeopleCode> Local string &CRLF; Local number &LoopNumber; &LoopNumber = 1024; &CRLF = Char(10) | Char(13);
While &LoopNumber > 0;
WinMessage(&LoopNumber | &CRLF); &LoopNumber = &LoopNumber / 2;
End-While; </lang>
Perl
<lang perl>my $n = 1024; while ($n) {
print "$n\n"; $n = int $n / 2;
}</lang>
until (condition)
is equivalent to while (not condition)
.
<lang perl>my $n = 1024; until ($n <= 0) {
print "$n\n"; $n = int $n / 2;
}</lang>
Perl 6
Here is a straightforward translation of the task description: <lang perl6>my $n = 1024; while $n > 0 { say $n; $n div= 2 }</lang>
The same thing with a C-style loop and a bitwise shift operator: <lang perl6>loop (my $n = 1024; $n > 0; $n +>= 1) { say $n }</lang>
And here's how you'd really write it, using a sequence operator that intuits the division for you:
<lang perl6>.say for 1024, 512, 256 ... 1</lang>
Phix
<lang Phix>integer i = 1024 while i!=0 do
?i i = floor(i/2) -- (see note)
end while</lang> note: using i=i/2 would iterate over 1000 times until i is 4.94e-324 before the final division made it 0, if it didn't typecheck when it got set to 0.5
PHL
<lang phl>var i = 1024; while (i > 0) { printf("%i\n", i); i = i/2; }</lang>
PHP
<lang php>$i = 1024; while ($i > 0) {
echo "$i\n"; $i >>= 1;
}</lang>
PicoLisp
<lang PicoLisp>(let N 1024
(while (gt0 N) (println N) (setq N (/ N 2)) ) )</lang>
Pike
<lang pike>int main(){
int i = 1024; while(i > 0){ write(i + "\n"); i = i / 2; }
}</lang>
PL/I
<lang PL/I>declare i fixed binary initial (1024);
do while (i>0);
put skip list (i); i = i / 2;
end;</lang>
Pop11
<lang pop11>lvars i = 1024; while i > 0 do
printf(i, '%p\n'); i div 2 -> i;
endwhile;</lang>
PostScript
PostScript has no real while
loop,
but it can easily be created with an endless loop and a check at the beginning:
<lang postscript>1024
{
dup 0 le % check whether still greater than 0 { pop exit } % if not, exit the loop if dup = % print the number 2 idiv % divide by two
} loop</lang>
PowerShell
<lang powershell>[int]$i = 1024 while ($i -gt 0) {
$i $i /= 2
}</lang>
Prolog
<lang prolog>while(0) :- !. while(X) :-
writeln(X), X1 is X // 2, while(X1).</lang>
Start the calculation at a top-level like this:
<lang prolog>?- while(1024).</lang>
PureBasic
<lang PureBasic>If OpenConsole()
x.i = 1024 While x > 0 PrintN(Str(x)) x / 2 Wend
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole()
EndIf</lang>
Python
<lang python>n = 1024 while n > 0:
print n n //= 2</lang>
R
<lang R>i <- 1024L while(i > 0) {
print(i) i <- i %/% 2
}</lang>
REBOL
<lang REBOL>REBOL [ Title: "Loop/While" Author: oofoe Date: 2009-12-19 URL: http://rosettacode.org/wiki/Loop/While ]
value: 1024 while [value > 0][ print value value: to-integer value / 2 ]</lang>
Racket
Loop/When
<lang racket>#lang racket (let loop ([n 1024])
(when (positive? n) (displayln n) (loop (quotient n 2))))</lang>
Macro
<lang racket>#lang racket (define-syntax-rule (while condition body ...)
(let loop () (when condition body ... (loop))))
(define n 0) (while (< n 10)
(displayln n) (set! n (add1 n)))</lang>
Retro
<lang Retro>1024 [ cr &putn sip 2 / dup ] while</lang>
REXX
version 1, simple
<lang rexx>/*REXX program demonstrates a DO WHILE with index reduction construct.*/ j=1024 /*define the initial value of J.*/
do while j>0 /*test if made at the top of DO.*/ say j j=j%2 /*in REXX, % is integer division.*/ end /*stick a fork in it, we're done.*/</lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
version 2, right justified
Note that a faster version could be implemented with
- DO WHILE x\==0
but that wouldn't be compliant with the wording of the task. <lang rexx>/*REXX program demonstrates a DO WHILE with index reduction construct.*/ x=1024 /*define the initial value of X.*/
do while x>0 /*test if made at the top of DO.*/ say right(x,10) /*pretty output by aligning right*/ x=x%2 /*in REXX, % is integer division.*/ end /*stick a fork in it, we're done.*/</lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
version 3, faster WHILE comparison
<lang rexx>/*REXX program demonstrates a DO WHILE with index reduction construct.*/ x=1024 /*define the initial value of X.*/
do while x>>0 /*this is an exact comparison. */ say right(x,10) /*pretty output by aligning right*/ x=x%2 /*in REXX, % is integer division.*/ end /*stick a fork in it, we're done.*/</lang>
output is the same as version 2.
version 4, index reduction
<lang rexx>/*REXX program demonstrates a DO WHILE with index reduction construct.*/
/* [↓] note: BY defaults to 1*/ do j=1024 by 0 while j>>0 /*this is an exact comparison. */ say right(j,10) /*pretty output by aligning right*/ j=j%2 /*in REXX, % is integer division.*/ end /*stick a fork in it, we're done.*/</lang>
output is the same as version 2.
Ring
<lang ring> i = 1024 while i > 0
see i + nl i = floor(i / 2)
end </lang>
Ruby
<lang ruby>i = 1024 while i > 0 do
puts i i /= 2
end</lang> The above can be written in one statement: <lang ruby>puts i = 1024 puts i /= 2 while i > 0</lang>
until condition
is equivalent to while not condition
.
<lang ruby>i = 1024 until i <= 0 do
puts i i /= 2
end</lang>
Run BASIC
<lang runbasic>i = 1024 while i > 0
print i i = int(i / 2)
wend end</lang>
Rust
<lang rust>fn main() {
let mut n: i32 = 1024; while n > 0 { println!("{}", n); n /= 2; }
}</lang>
SAS
<lang sas>data _null_; n=1024; do while(n>0);
put n; n=int(n/2);
end; run;</lang>
Sather
<lang sather>class MAIN is
main is i ::= 1024; loop while!(i > 0); #OUT + i + "\n"; i := i / 2; end; end;
end;</lang>
Scala
Imperative
<lang scala>var i = 1024 while (i > 0) {
println(i) i /= 2
}</lang>
Tail recursive
<lang scala> @tailrec
def loop(iter: Int) { if ((iter > 0)) { println(iter) loop(iter / 2) } } loop(1024)</lang>
Iterator
<lang scala> def loop = new Iterator[Int] {
var i = 1024 def hasNext = i > 0 def next(): Int = { val tmp = i; i = i / 2; tmp } } loop.foreach(println(_))</lang>
Stream
Finite stream (1024..0) filtered by takeWhile (1024..1). <lang scala> def loop(i: Int): Stream[Int] = i #:: (if (i > 0) loop(i / 2) else Stream.empty)
loop(1024).takeWhile(_ > 0).foreach(println(_))</lang>
Scheme
<lang scheme>(do ((n 1024 (quotient n 2)))
((<= n 0)) (display n) (newline))</lang>
Scilab
<lang>i=1024 while i>0
printf("%4d\n",i) i=int(i/2)
end</lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
Seed7
<lang seed7>$ include "seed7_05.s7i";
const proc: main is func
local var integer: i is 1024; begin while i > 0 do writeln(i); i := i div 2 end while; end func;</lang>
Sidef
<lang ruby>var i = 1024; while (i > 0) {
say i; i.div!(2).int!;
}</lang>
Slate
<lang slate>#n := 1024. [n isPositive] whileTrue:
[inform: number printString. n := n // 2]</lang>
Smalltalk
<lang smalltalk>number := 1024. [ number > 0 ] whileTrue:
[ Transcript print: number; nl. number := number // 2 ]</lang>
<lang smalltalk>number := 1024. [ number <= 0 ] whileFalse:
[ Transcript print: number; nl. number := number // 2 ]</lang>
Sparkling
<lang sparkling>var i = 1024; while i > 0 {
print(i); i /= 2;
}</lang>
Standard ML
<lang sml>val n = ref 1024; while !n > 0 do (
print (Int.toString (!n) ^ "\n"); n := !n div 2
)</lang>
But it is more common to write it in a tail-recursive functional style: <lang sml>let
fun loop n = if n > 0 then ( print (Int.toString n ^ "\n"); loop (n div 2) ) else ()
in
loop 1024
end</lang>
Suneido
<lang Suneido>i = 1024 while (i > 0)
{ Print(i) i = (i / 2).Floor() }</lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
Swift
<lang swift>var i = 1024 while i > 0 {
println(i) i /= 2
}</lang>
Tcl
<lang tcl>set i 1024 while {$i > 0} {
puts $i set i [expr {$i / 2}]
}</lang>
Plain TeX
<lang TeX> \newcount\rosetta \rosetta=1024 \loop
\the\rosetta\endgraf \divide\rosetta by 2 \ifnum\rosetta > 0
\repeat \bye </lang>
TI-83 BASIC
<lang ti83b>1024→I While I>0 Disp I I/2→I End </lang>
TI-89 BASIC
<lang ti89b>Local i 1024 → i While i > 0
Disp i intDiv(i, 2) → i
EndWhile</lang>
TorqueScript
This has to make use of mFloor because torque has automatic type shuffling, causing an infiniteloop. <lang Torque>%num = 1024; while(%num > 0) {
echo(%num); %num = mFloor(%num / 2);
}</lang>
Trith
<lang trith>1024 [dup print 2 / floor] [dup 0 >] while drop</lang> <lang trith>1024 [dup print 1 shr] [dup 0 >] while drop</lang>
TUSCRIPT
<lang tuscript>$$ MODE TUSCRIPT i=1024 LOOP
PRINT i i=i/2 IF (i==0) EXIT
ENDLOOP</lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
Unicon
See Icon.
Uniface
<lang Uniface>variables numeric I endvariables
I = 1024 while (I > 0) putmess I I = (I/2)[trunc] endwhile</lang>
UNIX Shell
<lang bash>x=1024 while $x -gt 0 ; do
echo $x x=$(( $x/2 ))
done</lang>
UnixPipes
<lang bash>(echo 1024>p.res;tail -f p.res) | while read a ; do
test $a -gt 0 && (expr $a / 2 >> p.res ; echo $a) || exit 0
done</lang>
Ursala
Unbounded iteration is expressed with the -> operator. An expression (p-> f) x, where p is a predicate and f is a function, evaluates to x, f(x), or f(f(x)), etc. as far as necessary to falsify p.
Printing an intermediate result on each iteration is a bigger problem because side effects are awkward. Instead, the function g in this example iteratively constructs a list of results, which is displayed on termination.
The argument to g is the unit list <1024>. The predicate p is ~&h, the function that tests whether the head of a list is non-null (equivalent to non-zero). The iterated function f is that which conses the truncated half of the head of its argument with a copy of the whole argument. The main program takes care of list reversal and formatting. <lang Ursala>#import nat
g = ~&h-> ^C/half@h ~&
- show+
main = %nP*=tx g <1024></lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1
Explicit iteration has its uses but there are always alternatives. The same output is produced by the following main program using bit manipulation. <lang Ursala>main = %nP*=tK33 1024</lang>
V
<lang v>1024 [0 >] [
dup puts 2 / >int
] while</lang>
Vedit macro language
<lang vedit>#1 = 1024 while (#1 > 0) {
Num_Type(#1) #1 /= 2
}</lang> or with for loop: <lang vedit>for (#1 = 1024; #1 > 0; #1 /= 2) {
Num_Type(#1)
}</lang>
Vim Script
<lang vim>let i = 1024 while i > 0
echo i let i = i / 2
endwhile</lang>
Visual Basic .NET
<lang vbnet>Dim x = 1024 Do
Console.WriteLine(x) x = x \ 2
Loop While x > 0</lang>
Wart
<lang wart>i <- 1024 while (i > 0)
prn i i <- (int i/2)</lang>
Whitespace
<lang Whitespace>
</lang> Pseudo-assembly equivalent: <lang asm>push 1024
0:
dup onum push 10 ochr push 2 div dup push 0 swap sub jn 0 pop exit</lang>
XLISP
The specification calls for an integer value and for the loop to run WHILE that value is greater than zero. In a dynamically typed language like XLISP, variables cannot be declared as integer or real; but the same result is obtained by looping WHILE the value of the variable i is greater than or equal to one. <lang xlisp>(DEFINE I 1024)
(WHILE (>= I 1)
(PRINT I) (DEFINE I (/ I 2)))</lang>
XPL0
<lang XPL0>code CrLf=9, IntOut=11; int I; [I:= 1024; while I>0 do
[IntOut(0, I); CrLf(0); I:= I>>1; \(same as I/2 for positive I) ];
]</lang>
zkl
<lang zkl>n:=1024; while(n>0){println(n); n/=2;}</lang>
- Output:
1024 512 256 128 64 32 16 8 4 2 1