Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to manually track a variables value during loops

 
ray hancock
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a special technique for keeping track of a variables value while its in a loop. For example, I frequently run into pop quiz questions like "what is the value of x" and then after a loop or two the value of x only gets mentally lost in translation for me.

So.. this an easy basic loop

for (int i = 1; i <= 10; i++) {
System.out.println(i);

So we all know the output would be something like this.. Really easy to follow along.
1
2
etc..

But what about those loops that are just brain teasers when It comes to manually keeping track of what a variable's value is, there has to be some kind of trick or technique for making this easier to keep track of. I'm starting college soon and I'm sure I'll run into similar quiz questions. Thanks so much you guys are amazing.


 
Marjorie Gyles
Ranch Hand
Posts: 42
Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I find simple pencil and paper handy for keeping track of them.
 
Rajdeep Biswas
Ranch Hand
Posts: 221
1
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Normally, on pen and paper as Lilith insisted. You can keep on striking off previous values as you write down the newer ones.
 
Winston Gutkowski
Bartender
Pie
Posts: 10417
63
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ray hancock wrote:But what about those loops that are just brain teasers when It comes to manually keeping track of what a variable's value is, there has to be some kind of trick or technique for making this easier to keep track of.

I think it would be useful if you could provide an example of a "brain-teaser" loop, because I'm still not quite sure what you're asking.

However, in general, there are a few things that you can do to make it easier to extract the sort of information you want to print out:

1. Write dumb code (←click) - that is to say: don't try to be too clever.

2. Don't write statements with compound actions. So:
Don't write:
element[i++] = someValue;
Instead write:
element[i] = someValue;
++i;


3. (similar to above) Don't use "unnamed" values for critical things, ie:
Don't write:
doSomethingWith(generateAValue(x, y, z));
Instead write:
Value v = generateAValue(x, y, z);
doSomethingWith(v);


The above just scratches the surface, but hopefully gives you a few thing to think about.

Winston
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic