SteveSteve
SteveSteve

Reputation: 13

Mirrored Triangle

I am required to display a mirrored triangle like so:

0 1 2
  0 1
    0

But I am only able to get

0 1 2 3
1 2 3
2 3
3

I am unsure of what I am doing wrong and everything I've looked at only shows the star pattern, no number patterns. here is my code.

for (int i = 0; i <= size; i ++) {
    for(int j = i; j <= size; j++) {
        System.out.print(j + " ");
    }
    System.out.println(" ");
}

Upvotes: 1

Views: 561

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

For each line, you have to print the leading spaces before printing the numbers. So you need two inner for loops, one for the spaces and one for the numbers:

for(int i = 0; i <= size; i++) {
    // first print out the leading spaces
    for(int j = 0; j < i; j++) {
        System.out.print("  ");
    }

    // then print out the numbers
    for(int j = 0; j <= size - i; j++) {
       System.out.print(j + " ");
    }

    System.out.println("");
}

Upvotes: 2

Related Questions