javafor-loopconsole-output

Need Help working with Nested For loop to display a block of text (Java)


I need to make a block of text that looks like this:

1 1 4

1 2 3

1 3 2

1 4 1

I have currently got this code:

for (int x = 1; x <= 4; x++) {
 for (int y = 4; y >= 1; y--) {
  System.out.println("1 " + x + " " + y);
 }
 System.out.println();
}

but it outputs the wrong thing, as

1 1 4

1 1 3

1 1 2

1 1 1

1 2 4

1 2 3

1 2 2

1 2 1

1 3 4

1 3 3

1 3 2

1 3 1

1 4 4

1 4 3

1 4 2

1 4 1

Can somebody help me? is it something with my loop syntax or something that has to do with the insides? Plus im new here, please dont be too harsh.


Solution

  • It is a little strange, but one way you can do this with a nested loop is to break out of the inner loop and to have the logic that zvxf has in the inner loop instead of as a variable:

    for (int x = 1; x <= 4; x++) {
            for (int y = 5-x; y >= 1; y--) {
            System.out.println("1 " + x + " " + y);
            break;
            }
        System.out.println();
    }
    

    Output:

    1 1 4
    
    1 2 3
    
    1 3 2
    
    1 4 1