Dredin 47
Dredin 47

Reputation: 21

need help understanding a loop in "head first c#"

I'm running through a book called "head first c#" and there's a part where it goes through loops that I need to figure out if they eventually end or run forever.

One of these loops the book says runs 8 times, however for the life of me it should run essentially forever.

the loop in question

It starts off with p and q equal, and runs while q is less than 32, because p is equal and not less than q it skips the while loop and goes straight to: q = p - q; which is q = 2 - 2; at this point the for loop finishes its first run and does q = q * 2; which is now q = 0 * 2;

At this point it is now impossible for q to ever go up and the for loop should run forever, and p will NEVER be less than q, meaning the while loop is never run....

So HOW THE HELL does it run 8 times?

I was expecting there to be a trick I was missing and read through it carefully a number of times but I can't find it.

Upvotes: 1

Views: 114

Answers (1)

Woody1193
Woody1193

Reputation: 7980

You're not quite correct here, because you're missing the fact that the loop invariant always runs last.

To help you understand what's going on here, let me break this down. When the loop starts, p and q are both 2.

  1. In the first iteration, you are correct that the while loop does not run, and therefore, q is updated to 0. The loop invariant then does q = q * 2, which updates it to 0.
  2. In the second iteration, again the while loop does not run. In this case, q is then set to p - q, which is 2. The loop invariant then does q = q * 2, which sets q to 4.
  3. In the third iteration, the while loop runs and updates p to 4. We then repeat the same operation as in step 1, and q is set to 0.
  4. In the fourth iteration, the loop operates similarly to the second iteration, and p - q results in 4. The loop invariant then does q = q * 2, which sets q to 8.

From this it's easy to see, that each odd iteration of the loop results in q being zero and p being equal to q and each even iteration results in q being set to 2 * p. Therefore, q will be equal to 32 after 8 iterations.

As an aside, if you're curious to see how a piece of code is working, you could always write it in C# and step into the code in Debugging Mode. Doing so would show you the value of all variables within scope after each line is executed.

Upvotes: 1

Related Questions