I am currently learning C and want to check if my understanding of the for
loop is correct.
Does the output A is 6
occur because after the 5th time the loop is run, the +1 is added to a
(which makes it 6), and then the condition is stopped because it is no longer <= 5
?
int a;
float b;
b = 0;
for (a = 1; a <= 5; a++)
b = b + 0.5;
printf ("A is %d\t\t B is %.2f\n", a, b);
Output is
A is 6 B is 2.50
Yes.
When a == 5
, the condition a <= 5
is true, so the body of the loop (b = b + 0.5;
) is executed. After the body, the a++
part is always executed.
This makes a == 6
. Then the condition a <= 5
is false
, so the loop terminates.
It is occasionally useful to use the value of the index after the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With