Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Writing a nest for loops out  RSS feed

 
Chad Palm
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

So, I struggle with writing loops out on paper for some reason. I try and do them out in my head and that does work very well either. Some loops I understand only because I've seen them before, but I was wondering if someone had a sure fire way/method/process for writing any nested or any loop out on a piece of paper. I've looked through books and online, but I see the same old ways.

example:



or like this:



I'm just curious how different people approach writing this out. I want to see how others 'make the sausage' instead of seeing the same old process over and over. Maybe that will help it click more in this brain.

Thanks for any help

*UPDATE*

Now I see someone using a table method, didn't see it when I searched, but now I see it linked. Thats one way to do it. I'm going to try that.
 
Junilu Lacar
Sheriff
Posts: 11125
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I gave one analogy a while ago that likened nested for-loops to an odometer. The loop in the deepest level nesting is the 1s place, the loop up from that is the 10s, then the 100s, and so on. The innermost loop "spins" the fastest and the most # of times. So in the nested for-loop example that you give, the statement on line 3 in the innermost with index j will be executed 50 times (5 x 10) while the statement on line 5 will be executed 5 times.

BTW, Java uses 0-based indices for arrays and other collections. If you're using the loop variables as index into arrays or collections, the initial value would be 0 instead of 1 and the loop condition would use < max in <= max. In your example, however, the use of 1 and <= max is quite all right.
 
Junilu Lacar
Sheriff
Posts: 11125
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Be careful about thinking "in the 10s" though. The odometer analogy kind of breaks down in that regard. If your loop limits were different, like this:

then it's not exactly like an odometer that counts by 10s. With this code, line 3 will be executed 21 times (3 x 7) while line 5 is only executed 3 times. Also note that the odometer analogy kind of breaks down when the increment is more than 1. That is, you can have a for-loop that counts by two, or three, or ten:

I'll leave it to you to figure out how many times the inner loop will get executed with this.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!