Search code examples
javaformatspacespascals-triangle

Format of Pascal's triangle


I have to print Pascal's Triangle, so it should have number 1 on each side, and format of triangle should be even on each side (now it's longer on the right side). My code:

public static void main(String[] args) {
    printPascalTriangle(10);
}

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

And the output is:

            0
           1 2
          2 3 4
         3 4 5 6
        4 5 6 7 8
       5 6 7 8 9 10
      6 7 8 9 10 11 12
     7 8 9 10 11 12 13 14
    8 9 10 11 12 13 14 15 16
   9 10 11 12 13 14 15 16 17 18
  10 11 12 13 14 15 16 17 18 19 20

Why it doesn't sum up? And why loop doesn't format spaces properly?


Solution

  • You should use printf method instead of print with proper arguments to format your output:

    public static void main(String[] args) {
        printPascalTriangle(10);
    }
    
    public static void printPascalTriangle(int rows) {
        for (int i = 0; i < rows; i++) {
            int number = 1;
            System.out.printf("%" + (rows - i) * 2 + "s", "");
            for (int j = 0; j <= i; j++) {
                System.out.printf("%4d", number);
                number = number * (i - j) / (j + 1);
            }
            System.out.println();
        }
    }
    

    Output:

                           1
                         1   1
                       1   2   1
                     1   3   3   1
                   1   4   6   4   1
                 1   5  10  10   5   1
               1   6  15  20  15   6   1
             1   7  21  35  35  21   7   1
           1   8  28  56  70  56  28   8   1
         1   9  36  84 126 126  84  36   9   1