Simple nested for loop example

后端 未结 7 530
后悔当初
后悔当初 2021-01-18 01:15

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++ ) {
            


        
7条回答
  •  臣服心动
    2021-01-18 01:47

    Let's look at what this would look like if we changed from loops to repeated code. First the outer loop:

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

    Now the inner loop:

    // First loop
    System.out.println( 1 + " " + 1 );
    System.out.println( 1 + " " + 2 );
    System.out.println( 1 + " " + 3 );
    // Second loop
    System.out.println( 2 + " " + 1 );
    System.out.println( 2 + " " + 2 );
    System.out.println( 2 + " " + 3 );
    // Third loop
    System.out.println( 3 + " " + 1 );
    System.out.println( 3 + " " + 2 );
    System.out.println( 3 + " " + 3 );
    

    Does it make sense now?

提交回复
热议问题