Pascal's Triangle Format

2019-01-18 05:01发布

The assignment is to create Pascal's Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the maximum number of rows the user wants printed.

public static void triangle(int maxRows) {
    int r, num;
    for (int i = 0; i <= maxRows; i++) {
        num = 1;
        r = i + 1;
        for (int col = 0; col <= i; col++) {
            if (col > 0) {
                num = num * (r - col) / col;    
            }
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

I need to format the values of the triangle such that it looks like a triangle:

              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

I can't for the life of me figure out how to do that. Please answer keeping in mind that I'm a beginner in Java programming.

8条回答
对你真心纯属浪费
2楼-- · 2019-01-18 05:39

You need to print the spaces (like others have mentioned) and also as this is homework I'm leaving it to you but you might want to look at this handy little function

System.out.printf();

Here is a handy reference guide

Also note that you will need to take into account that some numbers are more than 1 digit long!

查看更多
forever°为你锁心
3楼-- · 2019-01-18 05:41
public static long pascalTriangle(int r, int k)
{
    if(r == 1 || k <= 1 || k >= r) return 1L;
    return pascalTriangle(r-1, k-1) + pascalTriangle(r-1, k);
}

This method allows you to find the kth value of rth row.

查看更多
登录 后发表回答