c++ - Curly brackets after for statement -
i'm newbie. wrote code print sum of number 1 10. here's happened;
for(a = 1; a<=10; a++) sum += a; cout<<sum; executing gave me correct answer i.e 55
when execute following:
for(a = 1; a<=10; a++) { sum += a; cout<<sum; } it gives me complete different , wrong answer i.e 13610152128364555
why happen? goes wrong when put curly brackets after statement?
i hope not silly question.
if break apart big number:
1 3 6 10 15 21 28 36 45 55 you can see what's happening - it's outputting accumulated sum after every addition, because cout within loop. it's hard see because have no separator between numbers.
you'll see difference if format code properly:
for(a = 1; a<=10; a++) sum += a; // done each loop iteration cout<<sum; // done once @ end. for(a = 1; a<=10; a++) { sum += a; // done each loop iteration cout<<sum; // done each loop iteration }
Comments
Post a Comment