# nested for loops

Printable View

• 08-31-2009, 10:00 PM
Implode
nested for loops
Hello

Plz explain nested for loops.

This is my current understanding:

the outer for loop starts which has a nested for loop. The inner for loop loops and when done ...............

please explain if it returns to the outer for loop or the inner for loop.

thank you.
• 08-31-2009, 11:11 PM
mrmatt1111
Simple example of a nested loop:

Code:

```for(int j = 0; j < 3; j ++) {   System.out.println("Outer loop " + j + ".");   for(int i = 0; i < 3; i ++)   {       System.out.println("Inner loop " + i + ".");   } }```
Output:

Code:

```Outer loop 0. Inner loop 0. Inner loop 1. Inner loop 2. Outer loop 1. Inner loop 0. Inner loop 1. Inner loop 2. Outer loop 2. Inner loop 0. Inner loop 1. Inner loop 2.```
• 08-31-2009, 11:46 PM
Implode
thanks for the help, appreciate it. ;)
• 09-01-2009, 01:01 AM
steelshark
Try to imagine it like you we're drawing a chessboard:
you would do this with 2 nested for loops.
(for int i =0; i < 8; i++)
(for int j=0; j < 8 ;j++){
//code to draw
}
It will look like this:
I0J0 I0J1 I0J3 .... I0J7
I1J0 I1J2 ...
...
I7J0 I1J1 ... I7J7
Thus for one iteration on the outer for loop, you would go through the entire inner loop.
I hope this clarifies it a bit.
• 09-01-2009, 08:47 AM
Implode
Quote:

Originally Posted by steelshark
Try to imagine it like you we're drawing a chessboard:
you would do this with 2 nested for loops.
(for int i =0; i < 8; i++)
(for int j=0; j < 8 ;j++){
//code to draw
}
It will look like this:
I0J0 I0J1 I0J3 .... I0J7
I1J0 I1J2 ...
...
I7J0 I1J1 ... I7J7
Thus for one iteration on the outer for loop, you would go through the entire inner loop.
I hope this clarifies it a bit.

Perfectly explained, thank you