# Cannot figure out basic nested for loop

• 06-06-2013, 02:56 AM
no_slip_condition
Cannot figure out basic nested for loop
Code:

```for (int count = 0, count <=3; count++) for (int count2 = 0; count2 < count; count2++) System.out.println(count2);```
Iteration 1: count = 0, count2 = 0 , 0<0 = False->>> No output
Iteration 2: count = 1, count2 = 0, 0 < 1 = True--->>> 0
Iteration 3: count = 2, count2 = 0, 1 <2 = True -->>> 0
Iteration 4: count = 3, count2 = 1, 1 < 3 = True ->>>> 1
Iteration 5: count = Completed?, count2 = ?

I know that a 0 comes next, at some iteration, but from here I start getting confused.
• 06-06-2013, 03:29 AM
jim829
Re: Cannot figure out basic nested for loop
Sometimes it's best to just use a pencil and paper. Think about what the inner loop does for each value of count.
count = 0, inner loop immediately exits
count = 1, count2 = 0
count = 2, count2 = 0,
count = 2, count2 = 1
count = 3, count2 = 0
count = 3, count2 = 1
count = 3, count2 = 2

Regards,
Jim
• 06-06-2013, 03:40 AM
no_slip_condition
Re: Cannot figure out basic nested for loop
Believe me, I've tried many times, but my fundamental understanding is flawed. Why does the outer loop pause on 2? That makes no sense to me. If you run the outer loop by itself, it just goes 0, 1, 2, 3. I also don't get why count2 reverts to 0, does that occur because the outer loop stops at 3?
• 06-06-2013, 04:25 AM
sibernewf
Re: Cannot figure out basic nested for loop
The outer loop simply pauses while its iterating through the inner loop. Once the inner loop is finished, the outer loop increments by 1 then pauses while the inner loop goes again. and so on...

Hope that helps.
• 06-06-2013, 04:55 AM
jim829
Re: Cannot figure out basic nested for loop
A loop simply tells whatever is within the scope of the loop a certain number of times. If that happens to be another loop, then it repeats the inner loop a certain number of times. Try the following:

Code:

```for (int outer = 0; outer < 5; outer++) {   System.out.println("About to start inner loop, outer = " + outer);   for (int inner = 0; inner < 5; inner++) {       System.out.println("Inner loop running, inner = " + inner);   }   System.out.println("Inner loop done, returning to next iteration of outer loop"); }```
Another way to view your original nested loops is the following:

Code:

```for (int count2 = 0; count2 < 0; count2++) System.out.println(count2); for (int count2 = 0; count2 < 1; count2++) System.out.println(count2); for (int count2 = 0; count2 < 2; count2++) System.out.println(count2); for (int count2 = 0; count2 < 3; count2++) System.out.println(count2);```
Regards,
Jim
• 06-06-2013, 05:18 AM
no_slip_condition
Re: Cannot figure out basic nested for loop
Ahh, I get it now. Thank you very much guys. The example you posted helped a lot too.