Jump to content

simple for loop question


robokopf

Recommended Posts

hi guys, i was looking through the W3School Javascript For loop tutorial and the examples.

<html><body><script type="text/javascript">var i=0for (i=0;i<=10;i++){document.write("The number is " + i)document.write("<br />")}</script></body></html>

how do i perform an addition to add all the numbers from 0 to 10 and then display the result which is 55? any tips on this? should i use a for loop or a while loop? thanks in advance. :)

Link to comment
Share on other sites

You use a for loop if you know how many times the loop needs to run. If you don't know that, you use a while loop, which will run until some condition becomes false. So a for loop is used when you know how many times it needs to go, or else use a while loop. Since you know this loop needs to run 10 times, a for would work best.

ans = 0;for (i = 1; i <= 10; i++)  ans += i;alert(ans);

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...