Java ProgramsPatternsPrint Pascal's Triangle Pattern

Print Pascal's Triangle Pattern in Java

intermediate·  Patterns  ·  Number Patterns

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.

Input
rows = 5
Output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

Java Program

Java
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

1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

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.

How It Works
  1. 1Each row i gets rows - 1 - i leading spaces, shrinking as the rows get wider, the same centering technique used for a star pyramid.
  2. 2value starts at 1 — the first entry of every row — and is updated in place with value * (i - j) / (j + 1) after each number is printed, moving from one binomial coefficient to the next along the same row.
  3. 3That multiplicative step is what a combination formula does internally, applied one position at a time instead of computed fresh for each cell.
  4. 4No earlier row is ever read — unlike an additive build where row i depends on row i - 1, every row here is produced entirely from its own row index.
For row 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.

Complexity
Time Complexity: O(rows²)Space Complexity: O(1)

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.

Key Concepts

nested for loopbinomial coefficientleading spaces

Related Programs