Curly brackets after for statement

前端 未结 4 1524
渐次进展
渐次进展 2021-01-16 16:35

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<
<
相关标签:
4条回答
  • 2021-01-16 16:46

    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
    }
    
    0 讨论(0)
  • 2021-01-16 16:54

    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.

    0 讨论(0)
  • 2021-01-16 16:56

    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.

    0 讨论(0)
  • 2021-01-16 17:04

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

    0 讨论(0)
提交回复
热议问题