开发者

C Programming: Help Understanding for loop

On a practice test my professor gave me this program

#include <stdio.h&g开发者_如何转开发t;

int main (void)
{
    int i, sum;
    sum=0;
    for (i=1;i<=7;i++)
        sum=sum+i*i;
    printf("Rocky\n");
    printf("i is %d\n", i);
    printf("sum is %d\n",sum);

    return (0);
}

now, my question is: why is it that when I run this program the output is:

Rocky
i is 8
sum is 140

why is rocky only printed once? shouldn't it be printed as many times as i is printed?? UNDERSTOOD. THANKS TO ALL WHO HELPED :)


The problem is that without braces { }, the body of the loop is just the single line following the for statement.

So in this example the line sum=sum+i*i; gets executed 7 times, and the printf statements output the state of the variables after the loop has finished.


No. The for loop isn't in braces so it only executes the line right below it.

This will print everything within the braces however many times the loop runs

for (i=1;i<=7;i++)
{
    sum=sum+i*i;
    printf("Rocky\n");
    printf("i is %d\n", i);
    printf("sum is %d\n",sum);
}


No. Without brackets {} only the statement directly after the for loop is executed in the loop.

for (i=1;i<=7;i++)  
    sum=sum+i*i;

is the same as:

for (i=1;i<=7;i++) {
    sum=sum+i*i;
}


Per the edits made to the post, the Rocky printf line is outside the for loop and thus will not be repeated. I think you want something like this:

int main (void)
{
    int i, sum;
    sum=0;
    for (i=1;i<=7;i++)
    {
        sum=sum+i*i;
        printf("Rocky\n");
        printf("i is %d\n", i);
        printf("sum is %d\n",sum);
    }

    return (0);
}


 for (i=1;i<=7;i++)
    sum=sum+i*i;
 // ....

is same as

 for (i=1;i<=7;i++)
 {
    sum=sum+i*i;
 }
 //  ....


The default scope of the for loop is the immediate next statement after it.

So if written without the braces, the statement following the for loop will be executed only once (which is by default). If there is a need to execute more than one statement in a for loop, we use braces { }, all statements go inside these braces, which forms a "code-block".

E.g.:

     for ( bla; bla; bla; )
     {
        do this;
        and this; 
        and this as well;
     }

You can use as many code blocks you want in your program, with loops, control instructions, or maybe just by itself, it wont matter nor the compiler will throw an error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜