Paul Maxfield

Greenhorn

Posts: 7

posted 9 years ago

Sorry this may seem like a really dumb question but could someone explain to me how this works:

This is the code example I wrote from the book I'm studying:

The code out put is:

Now I understand where the 1 comes from but I don't understand where the 2 and 3 come from. The answer is probably so simple I'm missing it.

[edit]Add code tags. CR[/edit]

[ November 27, 2008: Message edited by: Campbell Ritchie ]

This is the code example I wrote from the book I'm studying:

The code out put is:

**Before the Loop**

In the Loop

Value of x is 1

In the Loop

Value of x is 2

In the Loop

Value of x is 3

This is after the loopIn the Loop

Value of x is 1

In the Loop

Value of x is 2

In the Loop

Value of x is 3

This is after the loop

Now I understand where the 1 comes from but I don't understand where the 2 and 3 come from. The answer is probably so simple I'm missing it.

[edit]Add code tags. CR[/edit]

[ November 27, 2008: Message edited by: Campbell Ritchie ]

posted 9 years ago

It is because of this line

As you know, while loops will continue iterating as long as the condition specified evaluates to true (x<4) in your case.

So for the first iteration you get

x=1 so x<4 is true

For the second you get (since you are incrementing x's value by 1)

x=2 so x<4 is true

For the third you get

x=3 so x<4 is true

After that x becomes 4 and x<4 is false. So the control exits the while loop and you get the "This is after the loop".

Don't worry about this. I still confuse the pre-increment and post-increment operators sometimes

[ November 26, 2008: Message edited by: Maneesh Godbole ]

Originally posted by Paul Maxfield:

.. but I don't understand where the 2 and 3 come from. The answer is probably so simple I'm missing it.

It is because of this line

As you know, while loops will continue iterating as long as the condition specified evaluates to true (x<4) in your case.

So for the first iteration you get

x=1 so x<4 is true

For the second you get (since you are incrementing x's value by 1)

x=2 so x<4 is true

For the third you get

x=3 so x<4 is true

After that x becomes 4 and x<4 is false. So the control exits the while loop and you get the "This is after the loop".

Sorry this may seem like a really dumb question

Don't worry about this. I still confuse the pre-increment and post-increment operators sometimes

[ November 26, 2008: Message edited by: Maneesh Godbole ]

Campbell Ritchie

Marshal

Posts: 56518

172

Gamini Sirisena

Ranch Hand

Posts: 378