MAIN

EN

Pascal's Triangle in Java

Two-dimensional array • Binomial coefficients
10.09.2021

Consider a variant of the implementation of Pascal’s triangle in Java. For the simplicity of storing and processing data, we represent the triangle as a two-dimensional array, in which the elements of the first row and column are equal to one, and all other elements are the sum of the two previous elements in the row and column.

A[i][j] = A[i][j-1] + A[i-1][j];

For example, if {n = 8} then the array will look like this:

  1  1  1  1  1  1  1  1
  1  2  3  4  5  6  7
  1  3  6 10 15 21
  1  4 10 20 35
  1  5 15 35
  1  6 21
  1  7
  1

Create and fill a two-dimensional array with decreasing row length:

int n = 8;
// array of 'n' rows
int[][] arr = new int[n][];
// iterate through the rows of the array
for (int i = 0; i < n; i++) {
    // row of 'n-i' elements
    arr[i] = new int[n - i];
    // iterate through the elements of the row
    for (int j = 0; j < n - i; j++) {
        if (i == 0 || j == 0) {
            // elements of the first row
            // and column are equal to one
            arr[i][j] = 1;
        } else {
            // all other elements are the sum of the two
            // previous elements in the row and column
            arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
        }
    }
}

Output the array row-wise:

// iterate through the array rows
for (int[] row : arr) {
    // iterate through the row elements
    for (int el : row)
        // space and two-digit number
        System.out.printf(" %2d", el);
    // line separator
    System.out.println();
}

© Golovin G.G., Code with comments, translation from Russian, 2021

Upward