-2

i just started learning C and don't understand why does the code segment below output 30. And why it doesn't output a number each iteration.

int k=3, f=3;
while (k<10)
     K++;
     f*=k;
printf("%d", f);

And when added curly braces it outputs 1814400, which in my opinion is the correct output

int k=3, f=3;
while (k<10){
     K++;
     f*=k;
}
printf("%d", f);

Could you explain why outputs are different?

1 Answers1

0

In the first snippet, this code

while (k<10)
    K++;

Increases k to 10. The next statement, f*=k;, is not part of the loop. So it gets executed after the loop, setting f to 30.

In your second snippet, both the K++; and f*=k; are part of the loop body, so both of them get executed each run through the loop.

It's more clear if you indent it properly:

int main()
{
    int k = 3, f = 3;
    while (k < 10)
        k++;
    f *= k;
    printf("%d", f);
}

Now it is clear that f *= k; isn't part of the loop in the first snippet.

For clarification, here's a documentation that explains the syntax:

while ( expression ) statement

Only the statement following the while() is part of the loop. With the braces {} you get a compound statement to be the loop's body.


Also note that k is not the same as K and it wouldn't compile this way, but I guess this is some auto-formatting that happened when you pasted the code.

Blaze
  • 16,736
  • 2
  • 25
  • 44