Loops/While

From Rosetta Code

Jump to: navigation, search
Loops/While is a programming task. Visitors like you are encouraged to solve it according to the task description, using any language they may happen to know.
Add to BlogMarksAdd to del.icio.usAdd to diggAdd to NewsvineAdd to redditAdd to Slashdot
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] 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 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

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] 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] 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] Befunge

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


[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

(while (> @i 0)
(println @i)
(dosync (ref-set i (quot @i 2))))</lisp>
 
=={{header|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>

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] D

import std.stdio;
 
int i = 1024;
void main() {
while(i > 0) {
writefln("%s", i);
i >>= 1;
}
}

[edit] E

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

[edit] Factor

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

[edit] FALSE

1024[$0>][$."
"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

[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

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

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

[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 [0 >] [dup putln 2 /] while.

[edit] Lisaac

+ i : INTEGER;
i := 1024;
{ i > 0 }.while_do {
i.print;
'\n'.print;
i := i / 2;
};

[edit] Logo

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

[edit] Lua

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

[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

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.html">i = 1024;
while (i.html">i > 0)
disp(i.html">i);
i.html">i = floor(i.html">i/2);
end

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

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

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

Works with: Rakudo version #21 "Seattle"

my Int $n = 2 * 1024;
while $n = $n div 2 {
say $n;
}

until condition is equivalent to while not condition.

my Int $n = 2 * 1024;
until ($n = $n div 2) <= 0 {
say $n;
}

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

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

Since PowerShell automatically converts variables to other types to accommodate for operations the above loop does not stop at 1 like it would in other languages but loops for quite a while until the value is small enough to be considered 0. An explicit cast corrects this:

$i = 1024
while ($i -gt 0) {
$i
[int]$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] REXX

Using integer division % here:

i = 1024
do while i > 0
say i
i = i % 2
end

[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] 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 | n: 1024.
[n isPositive] whileTrue:
[inform: number printString.
n: n // 2]] do

[edit] Smalltalk

number := 1024.
[ number > 0 ] whileTrue:
[ 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] 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
Personal tools
Google AdSense