You can create two iterative methods: one returns a 2d array containing Pascal's triangle, and the second returns the base of that triangle. It is more useful for clarity.
Output:
Insert n:
6
Pascal's triangle:
[1, 1, 1, 1, 1, 1]
[1, 2, 3, 4, 5]
[1, 3, 6, 10]
[1, 4, 10]
[1, 5]
[1]
Binomial coefficients:
[1, 5, 10, 10, 5, 1]
Code:
public static int[][] binomialTriangle(int n) {
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
IntStream.range(0, n).forEach(i -> {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the columns of the array
IntStream.range(0, n - i).forEach(j -> {
if (i == 0 || j == 0)
// first row and column
// are filled with ones
arr[i][j] = 1;
else
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
});
});
return arr;
}
public static int[] binomialCoefficient(int[][] triangle) {
return Arrays.stream(triangle)
// the last element in the row
.mapToInt(row -> row[row.length - 1])
.toArray();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Insert n:");
int n = scan.nextInt();
System.out.println("Pascal's triangle:");
int[][] arr = binomialTriangle(n);
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
int[] base = binomialCoefficient(arr);
System.out.println("Binomial coefficients:");
System.out.println(Arrays.toString(base));
}
See also: Convert negative index to positive index in an array (Trinomial Triangle)