Java – Simple nested for loop example

for-loopjava

Currently I am studying for my Java test. Whist studying I've come across a small problem.

In this for loop:

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

The output is:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

My problem is, I don't understand it. When I read this code I keep thinking it should look like this:

1 1
2 2
3 3

Why is this not the case?

Best Solution

Each iteration of i, you're starting a completely new iteration of j.

So, you start with i==1, then j==1,2,3 in a loop. Then i==2, then j==1,2,3 in a loop, etc.

Step through it one step at a time, and it will make sense.