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.