Task

Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).

If a number is 10, stop the loop after printing it, and do not generate any further numbers.

Otherwise, generate and print a second random number before restarting the loop.

If the number 10 is never generated as the first number in a loop, loop forever.



Related tasks

   Loop over multiple arrays simultaneously
   Loops/Break
   Loops/Continue
   Loops/Do-while
   Loops/Downward for
   Loops/For
   Loops/For with a specified step
   Loops/Foreach
   Loops/Increment loop index within loop body
   Loops/Infinite
   Loops/N plus one half
   Loops/Nested
   Loops/While
   Loops/with multiple ranges


/* To exit the innermost block, use return(<value>) */
 
block([n],
   do (
      n: random(20),
      ldisp(n),
      if n = 10 then return(),
      n: random(20),
      ldisp(n)
   )
)$
 
/* To exit any level of block, use catch(...) and throw(<value>);
they are not used for catching exceptions, but for non-local
return. Use errcatch(...) for exceptions. */
 
block([n],
   catch(
      do (
         n: random(20),
         ldisp(n),
         if n = 10 then throw('done),
         n: random(20),
         ldisp(n)
      )
   )
)$
 
/* There is also break(<value>, ...) in Maxima. It makes Maxima
stop the evaluation and enter a read-eval loop where one can change
variable values, then return to the function after exit; For example */
 
block([x: 1], break(), ldisp(x));
> x: 2;
> exit;
2