Jump to content

simple for loop question


robokopf
 Share

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...