CS: Tips for Reading Loops?

<p>So I'm self-studying with the Barron's book, right? And I realized something.</p>

<p>I am absolutely terrible at following loops. I can get them, but it usually takes a very long time, and often times I get an answer that's not one of the choices.</p>

<p>Anywho, if anyone has any strategies/tips/shortcuts for reading through loops, feel free to share them here! I'm sure a moderate number of people have the same problem that I have, and you'd be doing society a great favor by sharing your godly knowledge.</p>

<h1>I'll even give you an example you can talk through (ignore the dashes--CC doesn't like keeping the correct spacing).</h1>

<p>Consider this incredibly annoying code segment:</p>

<p>int x = 10, y = 0;
while (x > 5)
{
---y = 3;
---while (y < x)
---{
------y *= 2;
------if (y % x == 1)
--------y += x;
---}
---x -= 3;
}
System.out.println(x + " " + y);</p>

<p>What will be output after execution of this code segment?
(A) 1 6
(B) 7 12
(C) -3 12
(D) 4 12</p>

<h1>(E) -3 6</h1>

<p>The answer is (D).
Any tips on how to do this in a reasonably timely manner?</p>

<p>The way I always follow loops is with a table. I see 2 variables so I write on my page:



X  | Y
== | ==
10 | 0


Then as I work through the loop, I update each variable by writing its new value underneath it. By the time you finish working your way through the loop it should look like this:



X  | Y
== | ==
10 | 0
7  | 3
4  | 6
   | 12
   | 3
   | 6
   | 12


At the end you see the most updated value of X is 4 and the most updated value of Y is 12. So that’s what you write down. Don’t bother erasing and replacing, just every time a variable is updated, write its new value below. If a new variable shows up, add another column. Try this method and see how it works for you. Good luck!</p>

<p>



x  | y
== | ==
10 | 0
7  | 3
4  | 6
   | 12
   | 3
   | 6
   | 12


</p>

<p>Yeah, I’m self-studying, and I had the same issue. I asked my calc teacher (who has a master’s in computer science) for help, and he gave the same tip as DarkEyes. He told me that I would get nowhere by just following the code in my head–you have to write down charts like the one above in order to ensure that everything is correct.</p>