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.

1
  • What does the expected output represent? Commented Jan 26, 2022 at 1:20

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Wow thanks, I completely forgot about break, that helps a lot!
@GuandaoPrime No problem! Glad I could help.Don’t forget to click the check mark if this resolves your issue.
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();
}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.