Do while loop

Do while loop

This function introduces the Maths object and one of its methods, namely the random() method. This generates random numbers in the range 0 - 1. The program will loop so long as the random number is greater than the limit set. In this example 0.1. Once a number less than 0.1 is generated the program is to stop. Again I have no way of telling how many numbers will be printed. If I use a while loop, then if the first number generated is less than the limit I'll never enter the loop.

Since I want to write down at least one number the do .. while loop can be used as this doesn't test the condition until the end of the first loop.

codeView.png
  function test()
  {
     var limit = .1;
     var output = "<ol>";
     do 
     {
        var x = Math.random();
        output += "<li>" + x + "</li>";
     } while (x > 0.1);
     output += "</ol>";
     document.getElementById('output').innerHTML = output;
  }

Create the following test button to test the code

 <form>
   <input type="button" value = "test" onclick="test()" />
 </form>

Random numbers are used extensively in simulations and game playing.

Displaying HTML code examples in a browser

The do ... while loop provides another example of how the < and > symbols can be converted to their escape sequence by a short Javscript program. Manually having to do this tedious, and prone to error.

function test()
{
    var txt = document.getElementById('input').value;
    do
    { txt = txt.replace("<","&lt;");} while (txt.indexOf("<") >= 0)
    do
    { txt = txt.replace(">","&gt;");} while (txt.indexOf(">") >= 0)
    document.getElementById('output').value = txt;
}

Here is the corresponding form used by the second script

codeView.png
  <form action="javascript:test()">
  <h4>Input</h4>
  <textarea id="input" rows = "5" cols = "65"></textarea>
  <h4>Output</h4>
  <textarea id="output" rows="5" cols="65"> </textarea>
  <p><input type="submit" /></p>
  </form>
AttachmentSize
DoWhile.htm760 bytes
HTMLEscape.htm1011 bytes