Skip to content
Advertisement

Invert incrementing triangle pattern

I am writing some code that creates a incrementing number right angle triangle that looks something like this:

           1
         1 2
       1 2 3
     1 2 3 4
   1 2 3 4 5
 1 2 3 4 5 6

I am unsure on how to make my code output a triangle to that shape as my code outputs the same thing except inverted.

This is the code I have:

public class Main {
    public static void main(String[] args) {
        int rows = 6;
        for (int i = 1; i <= rows; ++i) {
            for (int j = 1; j <= i; ++j) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

My speculation is that instead of incrementing some of the values I would decrement them however the code would run infinite garbage values and not what I wanted.

Advertisement

Answer

It is needed to print some spaces before printing the numbers in each row, and the number of spaces should be decreasing depending on the row:

int rows = 6;

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

This prefix may be build using String::join + Collections::nCopies:

System.out.print(String.join("", Collections.nCopies(rows - i, "  ")));

Or since Java 11, this prefix may be replaced using String::repeat:

System.out.print("  ".repeat(rows - i));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement