Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    May 2007
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Problem with Do While loop

    I am trying to make a program that either alerts or at least prints the multiples of a number (which the user inputs into a text field). I am required to use a do while loop for this, so here is what I have so far.

    function factor() {
    var number= document.form.text.value
    var constant= document.form.text.value
    do {
    alert(number);
    number= number+constant
    } while (number <= 100);
    }


    // This line ends the HTML comment block -->

    </SCRIPT>
    </PRE>

    <BODY>
    <H1 align="center">Multiples<H1>
    <H2 align="center">Please enter a number between 1-10.</H1>
    <FORM name="form">
    <CENTER>
    <INPUT type="text" name="text">
    <br>
    <INPUT type="button" value="Show Multiples" onClick="factor();">
    </CENTER>
    </FORM>
    Last edited by Wilund; 05-08-2007 at 06:18 PM.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,318
    Thanks
    203
    Thanked 2,566 Times in 2,544 Posts
    Something like this?

    <SCRIPT type = "Text/JavaScript">
    function factor() {
    var number= parseInt(document.form.text.value); // otherwise number is a string and 2+ 2 = 22
    var mult = 0;
    do {
    mult ++;
    result = number * mult;
    alert ("Number is " + number + " Mult is " + mult + " Result is " + result);
    } while (result <= 100);

    }
    </SCRIPT>

    A do-while loop is often not a very good way of doing this sort of thing. A simple while loop is often better. Note that if result is 100 or less the loop will execute one more time, say 9 x 11 = 99, then 9 x 12 = 108. More generally, a do-while loop will always execute at least once as the test expression is not encountered until the end of the loop.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •