Hello and welcome to our community! Is this your first visit?
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
    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 {
    number= number+constant
    } while (number <= 100);

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


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

  2. #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    London, England
    Thanked 2,710 Times in 2,685 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);


    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