...

View Full Version : Problem with Do While loop



Wilund
05-08-2007, 05:12 PM
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>

Philip M
05-08-2007, 06:11 PM
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum