Steve
Steve

Reputation: 480

For loop beginner understanding

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

Upvotes: 3

Views: 103

Answers (2)

Erik Johnson
Erik Johnson

Reputation: 1164

You are correct. The for (init; condition; finish) language feature is a convenience for a structure that looks like this:

init;
while (condition) {
    ...insert code here...
    finish;
}

Upvotes: 2

Paul Boddington
Paul Boddington

Reputation: 37645

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.

Upvotes: 5

Related Questions