About while statements [closed]
I have a question. I need to create a script section with a while statement that prints all even numbers between 1 and 100 to the screen. I am most likely doing it wrong this is what I have
<script type="text/javascript">
Var count= 2;
while (count<=100) {
document.write (count +"<br />");
++count;
}
document.write("<p>You have printed 100 numbers.</p>");
</script>
I am trying to find something that could explain this better I also don开发者_C百科t know if I am suppose to use the do while either.
all even numbers from 1 to 100 is
var count= 2; //var lowercase!
while (count<=100) {
document.write (count +"<br />");
count+=2;
}
Maybe it will be more clear using the 'for' loop:
for(var count = 2; count <= 100; count += 2) {
document.write (count +"<br />");
}
An alternative approach is as follows:
<script type="text/javascript">
for (var i = 2; i <= 100; i += 2) { // edit: was i + 2
document.write(i + '<br />');
}
</script>
精彩评论