1. Member
Join Date
Aug 2009
Posts
50
Rep Power
0

## 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.

2. Simple example of a nested loop:

Java 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:

Java 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.```

3. Member
Join Date
Aug 2009
Posts
50
Rep Power
0
thanks for the help, appreciate it. ;)

4. Member
Join Date
Aug 2009
Posts
25
Rep Power
0
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.

5. Member
Join Date
Aug 2009
Posts
50
Rep Power
0
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