Loops/Break

From Rosetta Code
Revision as of 07:49, 6 June 2009 by rosettacode>Dmitry-kazakov (Ada solution added)
Task
Loops/Break
You are encouraged to solve this task according to the task description, using any language you may know.

Show a while loop which prints two random numbers (newly generated each loop) from 0 to 19 (inclusive). If the first number is 10, print it, stop the loop, and do not generate the second. Otherwise, loop forever.

Ada

<lang Ada> with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Discrete_Random;

procedure Test_Loop_Break is

  type Value_Type is range 1..20;
  package Random_Values is new Ada.Numerics.Discrete_Random (Value_Type);
  use Random_Values;
  Dice : Generator;
  A, B : Value_Type;

begin

  loop
     A := Random (Dice);
     Put_Line (Value_Type'Image (A));
     exit when A = 10;
     B := Random (Dice);
     Put_Line (Value_Type'Image (B));
  end loop;

end Test_Loop_Break; </lang>

BASIC

Works with: QuickBasic version 4.5

<lang qbasic>do

   a = int(rnd * 20)
   print a
   if a = 10 then exit loop 'EXIT FOR works the same inside FOR loops
   b = int(rnd * 20)
   print b

loop</lang>

Forth

<lang forth>include random.fs

main
 begin  20 random dup . 10 <>
 while  20 random .
 repeat ;

\ use LEAVE to break out of a counted loop

main
 100 0 do
   i random dup .
   10 = if leave then
   i random .
 loop ;

</lang>

Java

<lang java>import java.util.Random;

Random rand = new Random(); while(true){

   int a = rand.nextInt(20);
   System.out.println(a);
   if(a == 10) break;
   int b = rand.nextInt(20);
   System.out.println(b);

}</lang>

Python

<lang python>import random

while True:

   a = random.randrange(20)
   print a
   if a == 10:
       break
   b = random.randrange(20)
   print b</lang>

Ruby

<lang ruby>loop do

   a = rand(20)
   puts a
   if a == 10
       break
   end
   b = rand(20)
   puts b

end</lang>

Tcl

<lang tcl>while true {

   set a [expr int(20*rand())]
   puts $a
   if {$a == 10} {
       break
   }
   set b [expr int(20*rand())]
   puts $b

}</lang>