Print Pascal's Triangle Pattern in Java
Problem
Pascal's triangle can be displayed either as plain left-aligned rows of numbers or centered with leading spaces so the whole thing reads visually as a triangle — this version builds it centered, computing each row's binomial coefficients directly rather than from the row above.
Given a number of rows, print Pascal's triangle centered, so it forms a visible triangular shape.
Java Program
public class PascalsTrianglePattern {
public static void main(String[] args) {
int rows = 5;
for (int i = 0; i < rows; i++) {
StringBuilder line = new StringBuilder();
for (int s = 0; s < rows - 1 - i; s++) {
line.append(" ");
}
long value = 1;
for (int j = 0; j <= i; j++) {
if (j > 0) line.append(" ");
line.append(value);
value = value * (i - j) / (j + 1); // next binomial coefficient in the same row
}
System.out.println(line);
}
}
}Output
Core Logic
Computing each row's binomial coefficients directly, one after another within the same row, and centering the row with leading spaces, produces the triangle as an actual visual shape instead of a block of left-aligned numbers.
- 1Each row
igetsrows - 1 - ileading spaces, shrinking as the rows get wider, the same centering technique used for a star pyramid. - 2
valuestarts at1— the first entry of every row — and is updated in place withvalue * (i - j) / (j + 1)after each number is printed, moving from one binomial coefficient to the next along the same row. - 3That multiplicative step is what a combination formula does internally, applied one position at a time instead of computed fresh for each cell.
- 4No earlier row is ever read — unlike an additive build where row
idepends on rowi - 1, every row here is produced entirely from its own row index.
4 (0-indexed), value walks 1 → 4 → 6 → 4 → 1 as j advances from 0 to 4, landing on the same numbers Pascal's triangle always has in its fifth row.Key Point: Moving to the next binomial coefficient along a row costs one multiplication and one division, not a fresh calculation from scratch — that's what keeps this centered version just as efficient as a plain left-aligned build, while adding the leading-space shape on top.
Why: Each row computes its own values in O(1) per cell using only the previous cell in that same row, so the total work across all rows stays proportional to rows², without ever storing a previous row.