Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop beginner understanding

Tags:

c

loops

for-loop

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
like image 976
Steve Avatar asked Jan 08 '23 10:01

Steve


1 Answers

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.

like image 79
Paul Boddington Avatar answered Jan 17 '23 15:01

Paul Boddington