Jump to content


Check out our Community Blogs





- - - - -

Nested Loops

Posted by kmilton7, 02 July 2012 · 1560 views

novice loops examples beginner
Last week I finally downloaded Eclispe (Juno version), before I used notepad, but it was a real pain to manually compile and run. I like Eclipse - simple interface, easy to follow instructions, and presentation of one's errors on the side (not sure if it is a good thing for a newbie or not, at least it's helpful).

Well, it's Monday morning. Time to learn some theory. Need to go over nested loops. I do understand the notion of the first inner loop , but cannot grasp conceptually the second (and successive) inner loops. Let me give an example that is easy to follow.

Here is a simple code:

for (int i=0; i <3; i++){
System.out.println(i);
}


The output should be (sorry, I am at my internship, so cannot use eclipse, and cannot check the output of the code :mad: ):
0
1
2

Ok, but what if we add another loop within the first loop (inception or more appropriately "loopception" :P ). The abovementioned code with a slight addition:

for (int i=0; i<3; i++) {
for(int j=0; j<3; j++){
	 System.out.println(i + " " + j)
	 }
}

So let's think what the output is (keep in mind, i do not have Eclipse equiped at my intership, so I have to think through each example, thus, I strongly suggest to double check my "thinking"). Essentially, we have an output consisting of two columns - the first one is described by variable i, the second one by variable j.

Let's go through the though process. We have the first inner loop starting with 0, so we have:

i=0 j=0
i=0 j=1
i=0 j=2

After the inner loop is fully iterated for the first variable (i=0), the second value for the variable i "kicks in" (i=1). Thus, we have:

i=1 j=0
i=1 j=1
i=1 j=2

And so on... Therefore, the ouput is:

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

Well, after I went over the reasoning behind nested loops, I have a better idea of what it's all about. Hope this is helpful for a reader as well.

Here is a link for some good examples with nested loops (a bit more complicated than the one above):
http://forum.codecal..._+nested +loops

  • 0



Recent Entries

Recent Comments

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download