kaonashi kaonashi - 17 days ago 5
Java Question

How to invert a right triangle (Java)

i have a nested loop that prints a triangle of numbers like so:

123
12
1


and i need an another triangle, but it has to be inverted so the two can make an empty triangle underneath, like so:

12321
12 21
1 1


Here is my loop for the first one:

for (i = n; i >= 1; i--) {
System.out.println();
for (j = 1; j <= i; j++) {
System.out.print(j);
}
}
System.out.println();


I added another loop:

for (j = n; j >= 1; j--) {
System.out.print(j);
}


and the numbers are now reversed, but repeated, like so:

123321
12321
1321

Answer

This is my solution:

int n = 3;
for (int i = n; i >= 1; i--) {
    System.out.println();
    for (int j = n - 1; j > -n; j--) {
        int k = n - Math.abs(j);
        if (k <= i) {
            System.out.print(k);
        } else {
            System.out.print(" ");
        }
    }
}
System.out.println();
Comments