0

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.

3 Answers3

0

Your loop logic is incorrect. You have two loops and each runs 4 times so in total, your loop runs 16 times which isn't what you want. You want something like this.

for (int x = 1; x <= 4; x++) {
    int y = 4 - x + 1;
    System.out.println("1 " + x + " " + y);
    System.out.println();
}
jluims
  • 351
  • 2
  • 6
  • thank you, and I know that that is a solution, but I am required to use a nested for loop to make this, which is what I cant wrap my head around. I'm able to use a while or do/while loop, but regardless they need to be nested. – GuandaoPrime Jan 26 '22 at 00:29
0

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
Richard K Yu
  • 2,152
  • 3
  • 8
  • 21
0

Each loop will go on util the number reaches 4 or 1, maybe just write down the logic on the sketch paper first, my friend. :D