0

I'm a newbie. Wrote a code to print sum of number from 1 to 10. Here's what happened;

for(a = 1; a<=10; a++)
sum += a;
cout<<sum;

Executing that gave me the correct answer i.e 55

When I execute the following:

for(a = 1; a<=10; a++)
{
sum += a;
cout<<sum;
}

It gives me a complete different and wrong answer i.e 13610152128364555

Why does this happen? What goes wrong when I put curly brackets after for statement?

I hope this is not a silly question.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 8
    You're printing the number after every iteration... `1 3 6 10 15 21 28 36 45 55`, just without spaces. Seriously, a little bit of research / "googling" would have told you the answer. – Xeo May 22 '13 at 08:52
  • 1
    As always when such basic things remain unclear to someone I feel urged to suggest [a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). My suggestion for beginners: [Accelerated C++](http://www.amazon.com/dp/020170353X/?tag=stackoverfl08-20). – Fabio Fracassi May 22 '13 at 09:09

4 Answers4

10

If you break apart that big number:

1 3 6 10 15 21 28 36 45 55

you can see what's happening - it's actually outputting the accumulated sum after every addition, because your cout is within the loop. It's just hard to see because you have no separator between all those numbers.

You'll see the difference if you format your code properly:

for(a = 1; a<=10; a++)
    sum += a;             // Done for each loop iteration
cout<<sum;                // Done once at the end.

for(a = 1; a<=10; a++)
{
    sum += a;             // Done for each loop iteration
    cout<<sum;            // Done for each loop iteration
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    Got it. Thanks! Isn't it supposed to be for(a = 1; a<=10; a++) { sum += a; } cout< –  May 22 '13 at 08:57
  • @judas: Yes, but you don't _need_ the braces if there's only one statement in the body of the loop. – paxdiablo May 22 '13 at 09:00
5

because:

for(a = 1; a<=10; a++)
sum += a;
cout<<sum;

is like saying:

for(a = 1; a<=10; a++) {
    sum += a;
}
cout<<sum;

When you do this, it prints the number once rather than upon each iteration.

justin
  • 104,054
  • 14
  • 179
  • 226
0

In the first one you are executing cout<

In the second you are calling it every execution of the loop. That makes it print 1, then 3, then 6 ... always appending it, since there is no newline. As you can see you have 55 as last output.

Mike de Dood
  • 393
  • 1
  • 10
0

Because the code in curly braces is executed until the condition in for loop becomes false.

ZoomIn
  • 1,237
  • 1
  • 17
  • 35