...

View Full Version : logic problem



brlslngr
11-06-2009, 03:37 PM
im trying to add the following numbers: 0+1+2+3+4. The actual answer being 10 obviously. i dont realy get why its coming out as 5 and not 10.



var sum = 0;
for (i = 0; i < 5; i++);
{

sum = sum + i;
}

document.write("Sum is: " + sum);

abduraooft
11-06-2009, 03:40 PM
for (i = 0; i < 5; i++);
{

sum = sum + i;
}
The above block is equivalent to

for(i = 0; i < 5; i++)
;//do nothing
sum = sum + i;

Kor
11-06-2009, 04:06 PM
This is one of the reasons for I usually write a loop like:


for (i = 0; i < 5; i++){
sum = sum + i;
}

to avoid the temptation to close the line with a semicolon :)

Philip M
11-06-2009, 04:27 PM
This is one of the reasons for I usually write a loop like:


for (i = 0; i < 5; i++){
sum = sum + i;
}

to avoid the temptation to close the line with a semicolon :)

Agreed. The opening brace of a function/if/for should always be on the same line.

rnd me
11-06-2009, 11:15 PM
Agreed. The opening brace of a function/if/for should always be on the same line.

i second that, and add "return" to the list of things that should be on one line.

TinyScript
11-07-2009, 02:14 AM
LOL I didn't see the ; either.

Philip M
11-07-2009, 08:06 AM
Have a look at

http://www.howtocreate.co.uk/tutorials/javascript/semicolons

http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum