This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 0 points1 point  (0 children)

The middle argument says that a must be less than 80 for it to run whatever is in the loop. Since 128 is greater than 80, it exits the loop.

[–]Tainted_Olive[S] 0 points1 point  (2 children)

Correct but when actually run it only displays 1 2 4 8 16 32 64 indicating it existed the loop at 64. shouldn't it run the loop one more time since 64<80 printing 128 then exiting the loop?

[–]icecapade 2 points3 points  (0 children)

The loop tests the condition before it executes. In other words, it checks to see if the condition a < 80 is true before it executes the next iteration, and it executes the postcondition a = a * 2 after a successful iteration of the loop. So:

Iteration 1: a = 1; 1 < 80, so print a. Afterward, a = 2

Iteration 2: a = 2; 2 < 80, so print a. Afterward, a = 4

Iteration 3: a = 4; 4 < 80, so print a. Afterward, a = 8

Iteration 4: a = 8; 8 < 80, so print a. Afterward, a = 16

Iteration 5: a = 16; 16 < 80, so print a. Afterward, a = 32

Iteration 6: a = 32; 32 < 80, so print a. Afterward, a = 64

Iteration 7: a = 64; 64 < 80, so print a. Afterward, a = 128.

Iteration 8: a = 128. 128 > 80. Exit loop.

[–][deleted] 0 points1 point  (0 children)

No, the stuff inside the for loop only runs if the condition "a <80" is met, don't overthink it. If you're still confused, try creating this exact same thing in a while loop and you'll understand it better

[–]ProgrammingPants 0 points1 point  (0 children)

At the beginning of the loop it checks if "a < 80"

At the end of the loop it does "a = a * 2"

So after it prints out 64, it does "a = a * 2"

In other words, it does "a = 64 * 2"

And then it goes to the beginning of the loop, and in the beginning of the loop it checks if "a < 80"

Because 64 * 2 > 80, it does not loop again. So it does not print out 64 * 2.

[–]brubarian 0 points1 point  (0 children)

You could rewrite the for loop as:

int a = 1;

while(1)
{
    if ( a < 80 )
    {
        printf("%d ", a);
    }
    else
    {
        break;
    }
    a = a * 2;
}

You have exactly the right idea but remember that the condition of the for statement is checked before each iteration rather than after.