PDA

View Full Version : logic problem

brlslngr
11-06-2009, 04: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, 04: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, 05: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, 05: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-07-2009, 12:15 AM
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, 03:14 AM
LOL I didn't see the ; either.

Philip M
11-07-2009, 09: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/