Jump to content

  • Log In with Google      Sign In   
  • Create Account

Awesome job so far everyone! Please give us your feedback on how our article efforts are going. We still need more finished articles for our May contest theme: Remake the Classics


Stuck on For loop

Posted by Saint Retro, 12 February 2009 · 71 views

This highlights just how bad I am at maths.  I'm doing an exercise on chapter 2 and it gives you the following:
"What is the value of x after this code is done"

int x = 0
for (int y = 0; y <10; y+=2 )
{
   if( y == 4 )
     continue;
   x++
}

Now the answer is 4 but I don't see how.  I read it like this.  On the first loop y = 0 and so the code executes and x now = 1 and y = 2, on the second time round x = 2 and y is now 4, so the next time it tries to run it see's y is 4 and the continue means it goes back to the start without incrementing x thus meaning it would loop forever?

Edit: If someone could tell me how to do those little code windows as well that would be lovely.




continue skips the remainder of the for loop body; it's like hitting the for's closing } prematurely (so when y==4 the body of the for loop is skipped, x does not get incremented. y then gets incremented by two as normal and things continue from there).

Use [source lang="c#"]...[/source] tags for those scrolling code boxes. [smile]
Thanks for that, although I decided not to use it because it wouldn't display my '+' characters for some reason.
I understand the continue statement but I don't see how x=4 if the loop only loops what I believe to be 3 times.

int x = 0;
for (int y = 0; y < 10; y+=2 )
{
if( y == 4 )
continue;
x++;
}



Well, lets see...


Start:
x = 0, y = 0
Iteration 1:
Is y < 10? Yes, execute the loop body.
Is y == 4? No, y is 0.
Increment x; x is 1.
Add 2 to y; y is 2.
Iteration 2:
Is y < 10? Yes, execute the loop body.
Is y == 4? No, y is 2.
Increment x; x is 2.
Add 2 to y; y is 4.
Iteration 3:
Is y < 10? Yes, execute the loop body.
Is y == 4? Yes, y is 4. Skip the rest of the loop body.
Add 2 to y; y is 6.
Iteration 4:
Is y < 10? Yes, execute the loop body.
Is y == 4? No, y is 6.
Increment x; x is 3.
Add 2 to y; y is 8.
Iteration 5:
Is y < 10? Yes, execute the loop body.
Is y == 4? No, y is 8.
Increment x; x is 4.
Add 2 to y; y is 10.
Iteration 6:
Is y < 10? No, y is 10. Break out of the loop.
End:
x = 4, y = 10



That help? :)
i think so. So er does that mean the answer in the book is wrong or am i being blonde? No wait i got it! When it equals 4 it goes back to the top but then y is 6 hence why x gets incremented again! Great explanation thanks.
Quote:
Original post by Saint Retro
Thanks for that, although I decided not to use it because it wouldn't display my '+' characters for some reason.
This is a bug in the preview function; certain "special" characters vanish (including the plus sign). They post fine, however.
That's right! :)
PARTNERS