Loops/While

From Rosetta Code
Jump to: navigation, search
Task
Loops/While
You are encouraged to solve this task according to the task description, using any language you may know.
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.

Contents

[edit] 0815

<:400:~}:_:%<:a:~$=<:2:=/^:_:

[edit] 6502 Assembly

Code is called as a subroutine (i.e. JSR LoopsWhile). Specific OS/hardware routines for printing are left unimplemented.

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

[edit] ActionScript

var i:int = 1024;
while (i > 0) {
trace(i);
i /= 2;
}

[edit] Ada

declare
I : Integer := 1024;
begin
while I > 0 loop
Put_Line(Integer'Image(I));
I := I / 2;
end loop;
end;

[edit] ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d
INT i := 1024;
WHILE i > 0 DO
print(i);
i := i OVER 2
OD

Output:

      +1024       +512       +256       +128        +64        +32        +16         +8         +4         +2         +1

[edit] 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).

 
// print 1024 512 etc
def i := 1024;
while: { i > 0 } do: {
system.print(" "+i);
i := i/2;
}
 

[edit] AmigaE

PROC main()
DEF i = 1024
WHILE i > 0
WriteF('\d\n', i)
i := i / 2
ENDWHILE
ENDPROC

[edit] AppleScript

AppleScript does not natively support a standard out. Use the Script Editor's Event Log as the output.

set i to 1024
repeat while i > 0
log i
set i to i / 2
end repeat

[edit] Applesoft BASIC

 
10 I% = 1024
20 IF I% > 0 THEN PRINT I%:I% = I% / 2: GOTO 20
 

[edit] AutoHotkey

i = 1024
While (i > 0)
{
output = %output%`n%i%
i := Floor(i / 2)
}
MsgBox % output

[edit] AWK

BEGIN {
v = 1024
while(v > 0) {
print v
v = int(v/2)
}
}

[edit] BASIC

Works with: QuickBasic version 4.5
i = 1024
WHILE i > 0
PRINT i
i = i / 2
WEND

[edit] BBC BASIC

      i% = 1024
WHILE i%
PRINT i%
i% DIV= 2
ENDWHILE

[edit] Befunge

84*:*>   :v
^/2.:_@

[edit] Brat

Converts to integers so output is a little bit shorter and neater.

i = 1024
while { i > 0 } {
p i
i = (i / 2).to_i
}

[edit] C

int i = 1024;
while(i > 0) {
printf("%d\n", i);
i /= 2;
}

In for loop fashion:

int i;
for(i = 1024;i > 0; i/=2){
printf("%d\n", i);
}

[edit] C++

int i = 1024;
while(i > 0) {
std::cout << i << std::endl;
i /= 2;
}

Alternatively, it can be done with for:

for (int i = 1024; i>0; i /= 2)
std::cout << i << std::endl;

Indeed, in C++,

for (init; cond; update)
statement;

is equivalent to

{
init;
while (cond)
{
statement;
update;
}
}

[edit] C#

int i = 1024;
while(i > 0){
System.Console.WriteLine(i);
i /= 2;
}

[edit] Clojure

(def i (ref 1024))
 
(while (> @i 0)
(println @i)
(dosync (ref-set i (quot @i 2))))

2 ways without mutability:

(loop [i 1024]
(when (pos? i)
(println i)
(recur (quot i 2))))
 
 
(doseq [i (take-while pos? (iterate #(quot % 2) 1024))]
(println i))

[edit] ColdFusion

Remove the leading space from the line break tag.

With tags:

<cfset i = 1024 />
<cfloop condition="i GT 0">
#i#< br />
<cfset i /= 2 />
</cfloop>

With script:

<cfscript>
i = 1024;
while( i > 0 )
{
writeOutput( i + "< br/ >" );
}
</cfscript>

[edit] Common Lisp

(setq i 1024)
(loop while (> i 0) do
(print i)
(setq i (floor i 2)))

[edit] Crack

i = 1024;
while( i > 0 ) {
cout ` $i\n`;
i = i/2;
}
 

[edit] 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
 
'Note: Spacing is not an issue. I just find the code to be more readable with spaces.
 

[edit] D

import std.stdio;
 
void main() {
int i = 1024;
 
while (i > 0) {
writeln(i);
i >>= 1;
}
}
Output:
1024
512
256
128
64
32
16
8
4
2
1

[edit] 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.

1024[p2/d0<p]dspx

[edit] Dao

i = 1024;
while( i > 0 ) i = i / 2;
 

[edit] Delphi

var
i : Integer;
begin
i := 1024;
 
while i > 0 do
begin
Writeln(i);
i := i div 2;
end;
end;

[edit] DWScript

var i := 1024;
 
while i > 0 do begin
PrintLn(i);
i := i div 2;
end;

[edit] E

var i := 1024
while (i > 0) {
println(i)
i //= 2
}

[edit] EGL

x int = 1024;
while ( x > 0 )
SysLib.writeStdout( x );
x = MathLib.floor( x / 2 );
end

[edit] Erlang

%% Implemented by Arjun Sunel
-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).

[edit] 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
 

Even without the floor() the code will in fact end. But it's FAR beyond 1.

[edit] F#

let rec loop n = if n > 0 then printf "%d " n; loop (n / 2)
loop 1024

[edit] Factor

1024 [ dup 0 > ] [ dup . 2 /i ] while drop

[edit] FALSE

1024[$0>][$."
"2/]#%

[edit] Fantom

 
class Main
{
public static Void main ()
{
Int i := 1024
while (i > 0)
{
echo (i)
i /= 2
}
}
}
 

[edit] Forth

: halving ( n -- )
begin dup 0 >
while cr dup . 2/
repeat drop ;
1024 halving

[edit] Fortran

Works with: Fortran version 90 and later
INTEGER :: i = 1024
DO WHILE (i > 0)
WRITE(*,*) i
i = i / 2
END DO
Works with: Fortran version 77 and later
      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
 
C This is an alternative while loop with labels on both ends. This
C will use the condition as a break rather than create an entire
C IF block. Which you use is up to you, but be aware that you must
C use this one if you plan on allowing for breaks.
I = 1024
20 CONTINUE
C If condition is false, break.
IF (I .LE. 0) GOTO 30
C Handle I.
WRITE (*,*) I
I = I / 2
C Jump back to the "loop" beginning.
GOTO 20
30 CONTINUE
 
STOP
END

[edit] Frink

 
i=1024
while i>0
{
i = i/1
}
 

[edit] GML

i = 1024
while(i > 0)
{
show_message(string(i))
i /= 2
}

[edit] Go

i := 1024
for i > 0 {
fmt.Printf("%d\n", i)
i /= 2
}

[edit] Groovy

Solution:

int i = 1024
while (i > 0) {
println i
i /= 2
}

Output:

1024
512
256
128
64
32
16
8
4
2
1

[edit] Haskell

import Control.Monad (when)
main = loop 1024
where loop n = when (n > 0)
(do print n
loop (n `div` 2))

You could try to write a "while" that operates on monads:

import Control.Monad (when)
 
whileM :: (Monad m) => m Bool -> m a -> m ()
whileM cond body = do c <- cond
when c (body >> whileM cond body)

You can use it like this

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))

[edit] Icon and Unicon

procedure main()
local i
i := 1024
while write(0 < (i := i / 2))
end

[edit] Inform 7

let N be 1024;
while N > 0:
say "[N][line break]";
let N be N / 2;

[edit] 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
 
'Note: Spacing is not an issue. I just find the code to be more readable with spaces.
 

[edit] J

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

,. <.@-:^:*^:a: 1024

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).

monad define 1024
while. 0 < y do.
smoutput y
y =. <. -: y
end.
i.0 0
)

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.

[edit] Java

int i = 1024;
while(i > 0){
System.out.println(i);
i >>= 1; //also acceptable: i /= 2;
}

With a for loop:

for(int i = 1024; i > 0;i /= 2 /*or i>>= 1*/){
System.out.println(i);
}

[edit] JavaScript

var n = 1024;
while (n>0) {
print(n);
n/=2;
}

[edit] Joy

DEFINE putln == put '\n putch.
 
1024 [] [dup putln 2 /] while.

[edit] 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.
LabVIEW Loops While.png

[edit] Lang5

Translation of: Factor
: /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

[edit] 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.

 
i = 1024
while i > 0
print i
i = int( i / 2)
wend
end
 

[edit] Lisaac

+ i : INTEGER;
i := 1024;
{ i > 0 }.while_do {
i.println;
 
i := i / 2;
};

[edit]

make "n 1024
while [:n > 0] [print :n make "n :n / 2]

[edit] 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.

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

[edit] Lua

 
n = 1024
while n>0 do
print(n)
n = math.floor(n/2)
end
 

[edit] 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 (/).

 
> n := 1024: while n > 0 do print(n); n := iquo(n,2) end:
1024
 
512
 
256
 
128
 
64
 
32
 
16
 
8
 
4
 
2
 
1
 

[edit] 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:

i = 1024;
While[i > 0,
Print[i];
i = Floor[i/2];
]

[edit] 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.

i = 1024;
while (i > 0)
disp(i);
i = floor(i/2);
end

A vectorized version of the code is

  printf('%d\n', 2.^[log2(1024):-1:0]);    

[edit] 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);

[edit] MAXScript

a = 1024
while a > 0 do
(
print a
a /= 2
)

[edit] Make

NEXT=`expr $* / 2`
MAX=10
 
all: $(MAX)-n;
 
0-n:;
 
%-n: %-echo
@-make -f while.mk $(NEXT)-n MAX=$(MAX)
 
%-echo:
@echo $*

Invoking it

|make -f while.mk MAX=1024

[edit] Metafont

Metafont has no while loop, but it can be "simulated" easily.

a := 1024;
forever: exitif not (a > 0);
show a;
a := a div 2;
endfor

[edit] MIRC Scripting Language

alias while_loop {
var %n = 10
while (%n >= 0) {
echo -a Countdown: %n
dec %n
}
}

[edit] МК-61/52

1	0	2	4	П0	ИП0	/-/	x<0	15	ИП0
2 / П0 БП 05 С/П

[edit] Modula-2

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.

[edit] Modula-3

The usual module code and imports are omitted.

PROCEDURE DivBy2() =
VAR i: INTEGER := 1024;
BEGIN
WHILE i > 0 DO
IO.PutInt(i);
IO.Put("\n");
i := i DIV 2;
END;
END DivBy2;

[edit] MOO

i = 1024;
while (i > 0)
player:tell(i);
i /= 2;
endwhile

[edit] 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
 

[edit] Nimrod

var n: int = 1024
while n > 0:
echo(n)
n = n div 2

[edit] Nemerle

mutable x = 1024;
while (x > 0)
{
WriteLine($"$x");
x /= 2;
}

Or, with immutable types, after Haskell:

 
// within another function, eg Main()
def loop(n : int) : void
{
when (n > 0)
{
WriteLine($"$n");
loop(n / 2);
}
}
 
loop(1024)

[edit] Oberon-2

The usual module code and imports are ommited.

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;

[edit] Objeck

 
i := 1024;
while(i > 0) {
i->PrintLine();
i /= 2;
};
 

[edit] OCaml

let n = ref 1024;;
while !n > 0 do
Printf.printf "%d\n" !n;
n := !n / 2
done;;

But it is more common to write it in a tail-recursive functional style:

let rec loop n =
if n > 0 then begin
Printf.printf "%d\n" n;
loop (n / 2)
end
in loop 1024

[edit] Octave

i = 1024;
while (i > 0)
disp(i)
i = floor(i/2);
endwhile

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.

[edit] Oz

Oz' for-loop can be used in a C-like manner:

for I in 1024; I>0; I div 2 do
{Show I}
end

Alternatively, we can use the while feature of the for-loop with a mutable variable:

declare
I = {NewCell 1024}
in
for while:@I > 0 do
{Show @I}
I := @I div 2
end

[edit] 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
 

[edit] PARI/GP

n=1024;
while(n,
print(n);
n/=2
);

[edit] Pascal

program divby2(output);
 
var
i: integer;
 
begin
i := 1024;
while i > 0 do
begin
writeln(i);
i := i div 2
end
end.

[edit] Perl

my $n = 1024;
while ($n) {
print "$n\n";
$n = int $n / 2;
}

until (condition) is equivalent to while (not condition).

my $n = 1024;
until ($n <= 0) {
print "$n\n";
$n = int $n / 2;
}

[edit] Perl 6

Here is a straightforward translation of the task description:

my $n = 1024; while $n > 0 { say $n; $n div= 2 }

The same thing with a C-style loop and a bitwise shift operator:

loop (my $n = 1024; $n > 0; $n +>= 1) { say $n }

And here's how you'd really write it, using a sequence operator that intuits the division for you:

.say for 1024, 512, 256 ... 1

[edit] PHP

$i = 1024;
while ($i > 0) {
echo "$i\n";
$i >>= 1;
}

[edit] PicoLisp

(let N 1024
(while (gt0 N)
(println N)
(setq N (/ N 2)) ) )

[edit] Pike

int main(){
int i = 1024;
while(i > 0){
write(i + "\n");
i = i / 2;
}
}

[edit] PL/I

 
declare i fixed binary initial (1024);
 
do while (i>0);
put skip list (i);
i = i / 2;
end;
 

[edit] Pop11

lvars i = 1024;
while i > 0 do
printf(i, '%p\n');
i div 2 -> i;
endwhile;

[edit] PostScript

PostScript has no real while loop, but it can easily be created with an endless loop and a check at the beginning:

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

[edit] PowerShell

[int]$i = 1024
while ($i -gt 0) {
$i
$i /= 2
}

[edit] Prolog

while(0) :- !.
while(X) :- X>0,write(X), nl, X1 is X // 2, while(X1).

[edit] 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

[edit] Python

n = 1024
while n > 0:
print n
n //= 2

[edit] R

i <- 1024L
while(i > 0)
{
print(i)
i <- i %/% 2
}

[edit] 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
]

[edit] Racket

 
#lang racket
(let loop ([n 1024])
(when (positive? n)
(displayln n)
(loop (quotient n 2))))
 

[edit] Retro

1024 [ cr &putn sip 2 / dup ] while

[edit] REXX

[edit] version 1

/*REXX program to show a     DO  WHILE     construct. */   
j=1024
do while j>0
say j
j=j%2 /*in REXX, % is integer division. */
end

output

1024
512
256
128
64
32
16
8
4
2
1

[edit] version 2, right justified

Note that a faster version could be implemented with
DO WHILE x\==0
but that isn't compliant with the wording of the task.

/*REXX program to show a     DO  WHILE     construct. */
x=1024
do while x>0
say right(x,10) /*pretty up the output by aligning.*/
x=x%2 /*in REXX, % is integer division. */
end

output

      1024
       512
       256
       128
        64
        32
        16
         8
         4
         2
         1

[edit] version 3, faster WHILE comparison

/*REXX program to show a     DO  WHILE     construct. */
x=1024
do while x>>0 /*this is an exact comparison. */
say right(x,10) /*pretty up the output by aligning.*/
x=x%2 /*in REXX, % is integer division. */
end

output is the same as version 2.

[edit] Ruby

i = 1024
while i > 0 do
puts i
i /= 2
end

The above can be written in one statement (using the return value of the Kernel#puts method: nil is false), but the readability suffers:

i = 1024
puts i or i /= 2 while i > 0

until condition is equivalent to while not condition.

i = 1024
until i <= 0 do
puts i
i /= 2
end

[edit] Run BASIC

i = 1024
while i > 0
print i
i = int(i / 2)
wend
end

[edit] SAS

data _null_;
n=1024;
do while(n>0);
put n;
n=int(n/2);
end;
run;

[edit] Sather

class MAIN is
main is
i ::= 1024;
loop while!(i > 0);
#OUT + i + "\n";
i := i / 2;
end;
end;
end;

[edit] Scala

var i = 1024
while (i > 0) {
println(i)
i /= 2
}

[edit] Scheme

(do ((n 1024 (quotient n 2)))
((<= n 0))
(display n)
(newline))

[edit] 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;

[edit] Slate

 
#n := 1024.
[n isPositive] whileTrue:
[inform: number printString.
n := n // 2]
 

[edit] Smalltalk

number := 1024.
[ number > 0 ] whileTrue:
[ Transcript print: number; nl.
number := number // 2 ]
number := 1024.
[ number <= 0 ] whileFalse:
[ Transcript print: number; nl.
number := number // 2 ]

[edit] Standard ML

val n = ref 1024;
while !n > 0 do (
print (Int.toString (!n) ^ "\n");
n := !n div 2
)

But it is more common to write it in a tail-recursive functional style:

let
fun loop n =
if n > 0 then (
print (Int.toString n ^ "\n");
loop (n div 2)
) else ()
in
loop 1024
end

[edit] Suneido

i = 1024
while (i > 0)
{
Print(i)
i = (i / 2).Floor()
}

Output:

1024
512
256
128
64
32
16
8
4
2
1

[edit] Tcl

set i 1024
while {$i > 0} {
puts $i
set i [expr {$i / 2}]
}

[edit] TI-89 BASIC

Local i
1024 → i
While i > 0
Disp i
intDiv(i, 2) → i
EndWhile

[edit] TorqueScript

This has to make use of mFloor because torque has automatic type shuffling, causing an infiniteloop.

%num = 1024;
while(%num > 0)
{
echo(%num);
 %num = mFloor(%num / 2);
}

[edit] Trith

1024 [dup print 2 / floor] [dup 0 >] while drop
1024 [dup print 1 shr] [dup 0 >] while drop

[edit] TUSCRIPT

 
$$ MODE TUSCRIPT
i=1024
LOOP
PRINT i
i=i/2
IF (i==0) EXIT
ENDLOOP
 

Output:

1024
512
256
128
64
32
16
8
4
2
1 

[edit] Unicon

See Icon.

[edit] UNIX Shell

Works with: Bourne Again SHell
x=1024
while [[ $x -gt 0 ]]; do
echo $x
x=$(( $x/2 ))
done

[edit] UnixPipes

(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

[edit] 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.

#import nat
 
g = ~&h-> ^C/half@h ~&
 
#show+
 
main = %nP*=tx g <1024>

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.

main = %nP*=tK33 1024

[edit] V

1024 [0 >] [
dup puts
2 / >int
] while

[edit] Vedit macro language

#1 = 1024
while (#1 > 0) {
Num_Type(#1)
#1 /= 2
}

or with for loop:

for (#1 = 1024; #1 > 0; #1 /= 2) {
Num_Type(#1)
}

[edit] Visual Basic .NET

Dim x = 1024
Do
Console.WriteLine(x)
x = x \ 2
Loop While x > 0

[edit] Whitespace

   	          
 












 
 
 

Pseudo-assembly equivalent:

push 1024
 
0:
dup onum push 10 ochr
push 2 div dup
push 0 swap sub
jn 0
pop exit

[edit] 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)
];
]
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox