Loops/While: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Ruby}}: added until)
m (Fixed lang tags.)
Line 2:
 
=={{header|ActionScript}}==
<lang actionscript>var i:int = 1024;
var i:int = 1024;
while (i > 0) {
trace(i);
i /= 2;
}</lang>
}
</lang>
 
=={{header|Ada}}==
<lang ada>declare
declare
I : Integer := 1024;
begin
Line 19 ⟶ 16:
I := I / 2;
end loop;
end;</lang>
</lang>
 
=={{header|ALGOL 68}}==
Line 26 ⟶ 22:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>INT i := 1024;
<pre>
INT i := 1024;
WHILE i > 0 DO
print((i));
i := i OVER 2
OD</lang>
</pre>
Output:
<lang algol68>+1024 +512 +256 +128 +64 +32 +16 +8 +4 +2 +1</lang>
<pre>
+1024 +512 +256 +128 +64 +32 +16 +8 +4 +2 +1
</pre>
 
=={{header|AmigaE}}==
Line 48 ⟶ 40:
 
=={{header|AutoHotkey}}==
<lang AutoHotkey>i = 1024
i = 1024
While (i > 0)
{
Line 55 ⟶ 46:
i := Floor(i / 2)
}
MsgBox % output</lang>
</lang>
 
=={{header|AWK}}==
Line 76 ⟶ 66:
 
=={{header|Befunge}}==
<lang befunge>84*:*> :v
^/2.:_@</lang>
 
 
Line 99 ⟶ 89:
}</lang>
Alternatively, it can be done with <code>for</code>:
<lang cpp>for (int i = 1024; i>0; i /= 2)
std::cout << i << std::endl;</lang>
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>
for (init; cond; update)
statement;
</lang>
is equivalent to
<lang cpp>{
{
init;
while (cond)
Line 117 ⟶ 102:
update;
}
}</lang>
}
</lang>
 
=={{header|C sharp|C#}}==
<lang ccsharp>int i = 1024;
while(i > 0){
System.Console.WriteLine(i);
Line 131 ⟶ 115:
 
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>
 
=={{header|Common Lisp}}==
Line 171 ⟶ 155:
 
=={{header|FALSE}}==
<lang false>1024[$0>][$."
"2/]#%</lang>
 
=={{header|Forth}}==
<lang forth>: halving ( n -- )
begin dup 0 >
: halving ( n -- )
while begin cr dup 0. > 2/
repeat drop ;
while cr dup . 2/
1024 halving</lang>
repeat drop ;
1024 halving
</lang>
 
=={{header|Factor}}==
<lang factor>1024 [ dup 0 > ] [ dup . 2 /i ] [ drop ] while</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<lang fortran>INTEGER :: i = 1024
INTEGERDO ::WHILE (i => 10240)
WRITE(*,*) i
DO WHILE (i > 0)
i WRITE(*,*)= i / 2
END DO</lang>
i = i / 2
END DO
</lang>
 
=={{header|Haskell}}==
Line 224 ⟶ 204:
 
=={{header|Icon}}==
<lang icon>procedure main()
local i
procedure main()
i local:= i1024
while write(0 < (i := 1024i / 2))
end</lang>
while write(0 < (i := i / 2))
end
</lang>
 
=={{header|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>
,. <.@-:^:*^: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>3 : 0 ] 1024
3 : 0 ] 1024
while. 0 < y do.
y 1!:2 ] 2
y =. <. -: y
end.
i. 0 0
)</lang>
)
</lang>
 
Though it's rare to see J code like this.
Line 274 ⟶ 248:
 
=={{header|Joy}}==
<lang joy>DEFINE putln == put '\n putch.
DEFINE putln == put '\n putch.
 
1024 [0 >] [dup putln 2 /] while.</lang>
</lang>
 
=={{header|Lisaac}}==
<lang Lisaac>+ i : INTEGER;
+ i : INTEGER;
i := 1024;
{ i > 0 }.while_do {
Line 288 ⟶ 259:
'\n'.print;
i := i / 2;
};</lang>
</lang>
 
=={{header|Logo}}==
<lang logo>make "n 1024
while [:n > 0] [print :n make "n :n / 2]</lang>
 
=={{header|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,
i = 1024;
WhilePrint[i > 0,];
i = PrintFloor[i/2];
]</lang>
i = Floor[i/2];
]
</lang>
 
=={{header|MAXScript}}==
<lang maxscript>a = 1024
<pre>
a = 1024
while a > 0 do
(
print a
a /= 2
)</lang>
)
</pre>
 
=={{header|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>
 
=={{header|Metafont}}==
Line 355 ⟶ 321:
 
=={{header|MOO}}==
<lang moo>i = 1024;
i = 1024;
while (i > 0)
player:tell(i);
Line 400 ⟶ 365:
 
=={{header|Pascal}}==
<lang pascal>program divby2(output);
program divby2(output);
 
var
Line 413 ⟶ 377:
i := i div 2
end
end.</lang>
</lang>
 
=={{header|Perl}}==
Line 437 ⟶ 400:
while $n = $n div 2 {
say $n;
}</lang>
}
</lang>
 
<code>until ''condition''</code> is equivalent to <code>while not ''condition''</code>.
Line 455 ⟶ 417:
 
=={{header|Pop11}}==
<lang pop11>lvars i = 1024;
<pre>
lvars i = 1024;
while i > 0 do
printf(i, '%p\n');
i div 2 -> i;
endwhile;</lang>
</pre>
 
=={{header|PowerShell}}==
Line 487 ⟶ 447:
 
=={{header|R}}==
<lang R>i <- 1024L
i <- 1024L
while(i > 0)
{
print(i)
i <- i %/% 2
}</lang>
}
</lang>
 
=={{header|Ruby}}==
Line 515 ⟶ 473:
 
=={{header|Scheme}}==
<lang scheme>(do ((n 1024 (quotient n 2)))
(do ((n 1024 (quotient n 2)))
((<= n 0))
(display n)
Line 522 ⟶ 479:
 
=={{header|Slate}}==
<lang slate>[| n | n: 1024.
[| n | n: 1024.
[n isPositive] whileTrue:
[inform: number printString.
n: n // 2]] do</lang>
</lang>
 
=={{header|Smalltalk}}==
Line 562 ⟶ 517:
=={{header|TI-89 BASIC}}==
 
<prelang style="font-family:'TI Uni'"ti89b>Local i
1024 → i
While i > 0
Disp i
intDiv(i, 2) → i
EndWhile</prelang>
 
=={{header|UNIX Shell}}==
Line 578 ⟶ 533:
 
=={{header|UnixPipes}}==
<lang shbash> (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>
 
=={{header|Ursala}}==
Line 598 ⟶ 553:
whole argument. The main program takes care of list reversal and
formatting.
<lang Ursala>#import nat
#import nat
 
g = ~&h-> ^C/half@h ~&
Line 605 ⟶ 559:
#show+
 
main = %nP*=tx g <1024></lang>
</lang>
output:
<pre>
Line 624 ⟶ 577:
The same output is produced by the following main program
using bit manipulation.
<lang Ursala>main = %nP*=tK33 1024</lang>
main = %nP*=tK33 1024
</lang>
 
=={{header|V}}==
<lang v> 1024 [0 >] [
dup puts
2 / >int
] while</lang>
 
=={{header|Vedit macro language}}==
Line 639 ⟶ 590:
Num_Type(#1)
#1 /= 2
}</lang>
}
</lang>
or with for loop:
<lang vedit>for (#1 = 1024; #1 > 0; #1 /= 2) {

Revision as of 23:10, 20 November 2009

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.

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>

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

<lang algol68>INT i := 1024; WHILE i > 0 DO

  print((i));
  i := i OVER 2

OD</lang> Output: <lang algol68>+1024 +512 +256 +128 +64 +32 +16 +8 +4 +2 +1</lang>

AmigaE

<lang amigae>PROC main()

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

ENDPROC</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>

BASIC

Works with: QuickBasic version 4.5

<lang qbasic>i = 1024 while i > 0

  print i
  i = i / 2

wend</lang>

Befunge

<lang befunge>84*:*> :v

    ^/2.:_@</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>

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>

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>

D

<lang d>import std.stdio;

int i = 1024; void main() {

   while(i > 0) {
       writefln("%s", i);
       i >>= 1;
   }

}</lang>

E

<lang e>var i := 1024 while (i > 0) {

   println(i)
   i //= 2

}</lang>

FALSE

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

Forth

<lang forth>: halving ( n -- )

 begin  dup 0 >
 while  cr dup .  2/
 repeat drop ;

1024 halving</lang>

Factor

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

Fortran

Works with: Fortran version 90 and later

<lang fortran>INTEGER :: i = 1024 DO WHILE (i > 0)

 WRITE(*,*) i
 i = i / 2

END DO</lang>

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

<lang icon>procedure main()

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

end</lang>

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>3 : 0 ] 1024

    while. 0 < y do.
         y 1!:2 ] 2
         y =. <. -: y 
    end.

   i. 0 0

)</lang>

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

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>

Joy

<lang joy>DEFINE putln == put '\n putch.

1024 [0 >] [dup putln 2 /] while.</lang>

Lisaac

<lang Lisaac>+ i : INTEGER; i := 1024; { i > 0 }.while_do {

 i.print;
 '\n'.print;
 i := i / 2;

};</lang>

<lang logo>make "n 1024 while [:n > 0] [print :n make "n :n / 2]</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>

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

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>

MOO

<lang moo>i = 1024; while (i > 0)

 player:tell(i);
 i /= 2;

endwhile</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>

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.

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>

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

Works with: Rakudo version #21 "Seattle"

<lang perl6>my Int $n = 2 * 1024; while $n = $n div 2 {

   say $n;

}</lang>

until condition is equivalent to while not condition.

<lang perl6>my Int $n = 2 * 1024; until ($n = $n div 2) <= 0 {

   say $n;

}</lang>

PHP

<lang php>$i = 1024; while ($i > 0) {

  echo "$i\n";
  $i >>= 1;

}</lang>

Pop11

<lang pop11>lvars i = 1024; while i > 0 do

   printf(i, '%p\n');
   i div 2 -> i;

endwhile;</lang>

PowerShell

<lang powershell>$i = 1024 while ($i -gt 0) {

   $i
   $i /= 2

}</lang> 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: <lang powershell>$i = 1024 while ($i -gt 0) {

   $i
   [int]$i /= 2

}</lang>

Prolog

<lang prolog>while(0) :- !. while(X) :- write(X), nl, X1 is X // 2, while(X1).</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>

Ruby

<lang ruby>i = 1024 while i > 0 do

  puts i
  i /= 2

end</lang> The above can be written in one statement (using the return value of the Kernel#puts method: nil is false), but the readability suffers: <lang ruby>i = 1024 puts i or 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>

Scheme

<lang scheme>(do ((n 1024 (quotient n 2)))

   ((<= n 0))
   (display n)
   (newline))</lang>

Slate

<lang slate>[| n | n: 1024.

 [n isPositive] whileTrue: 
   [inform: number printString.
    n: n // 2]] do</lang>

Smalltalk

<lang smalltalk>number := 1024. [ number > 0 ] whileTrue:

 [ Transcript print: number; nl.
 number := number // 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>

Tcl

<lang tcl>set i 1024 while {$i > 0} {

   puts $i
   set i [expr {$i / 2}]

}</lang>

TI-89 BASIC

<lang ti89b>Local i 1024 → i While i > 0

 Disp i
 intDiv(i, 2) → i

EndWhile</lang>

UNIX Shell

Works with: Bourne Again 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 ~&

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

Visual Basic .NET

<lang vbnet>Dim x = 1024 Do

   Console.WriteLine(x)
   x = x \ 2

Loop While x > 0</lang>