Easy Logical Thinking Java

Pascal Triangle in Java

Print the first n rows of Pascal's triangle.

  • TimeO(n^2)
  • SpaceO(1)
  • Hints3
  • Read4 min
Quick answer

To print a Pascal triangle in Java, start each row with 1 and get the next value using value = value * (row - col) / (col + 1), with rows and columns counted from 0. This needs no array and takes O(n^2) time. You can also add the two numbers above each cell in a 2D array.

Nested loopsBinomial coefficientsRecursion
1

Problem statement

A Pascal triangle in Java is a useful loop and array exercise. Given n, print the first n rows of the triangle.

Every row starts and ends with 1. Every other number is the sum of the two numbers just above it. With rows and columns counted from 0, the value is also row! / (col! * (row - col)!), known as "row choose col".

Input

An integer n, the number of rows.

Output

n rows of Pascal's triangle, centred with leading spaces.

Examples

Example 1
Inputn = 3
Output1 / 1 1 / 1 2 1

The 2 is 1 + 1 from the row above. A slash marks a new line here.

Example 2
Inputn = 5, last row
Output1 4 6 4 1

From 1 3 3 1 above: 1+3=4, 3+3=6, 3+1=4.

Constraints

  • 0 <= n <= 30, so that every value fits in an int
  • Rows and columns are counted from 0
2

Think before you code

Reveal the questions to ask yourself first
  • Can you get row 4 from row 3 alone?
  • Can you get a value from its left neighbour without the row above?
  • What happens to the multiplication as rows grow?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Fill the first and last cell of each row with 1.
2 Hint 2
Middle cell = cell above-left + cell above.
3 Hint 3
Without an array: next = current * (row - col) / (col + 1). Multiply first, then divide.
4

Approach

Reveal the step-by-step approach
Method Idea Time Extra space
For loop formula Get each value from its left neighbour O(n²) O(1)
1D array Update one row in place, right to left O(n²) O(n)
2D array Add the two cells above O(n²) O(n²)
Plain recursion value(r, c) = value(r-1, c-1) + value(r-1, c) O(2ⁿ) O(n) stack

Formula steps:

  1. For each row, print n - row - 1 spaces to centre it.
  2. Set value = 1.
  3. For each column, print value, then set value = value * (row - col) / (col + 1).

The division is always exact because the result is a binomial coefficient. The loop style is the same as in pattern programs.

5

Dry run

Walk through the example step by step

Row 4 with the formula, starting at value = 1:

col | print | next value
----+-------+---------------------------
0   | 1     | 1 * 4 / 1 = 4
1   | 4     | 4 * 3 / 2 = 6
2   | 6     | 6 * 2 / 3 = 4
3   | 4     | 4 * 1 / 4 = 1
4   | 1     | 1 * 0 / 5 = 0 (not printed)
6

Solution

Reveal the full Java solution
Solution.java
public class PascalTriangle {
    static void print(int n) {
        for (int row = 0; row < n; row++) {
            for (int s = 0; s < n - row - 1; s++) {
                System.out.print(" ");
            }
            long value = 1;
            for (int col = 0; col <= row; col++) {
                System.out.print(value + " ");
                value = value * (row - col) / (col + 1);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        print(5);
    }
}

This is the Pascal triangle in Java using for loop only. Output:

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

value is a long because the product before the division can be too big for an int.

Pascal triangle in Java using 2D array

A jagged array fits well because row r has r + 1 cells. See arrays in Java if this is new.

import java.util.Arrays;

public class Pascal2D {
    public static void main(String[] args) {
        int n = 5;
        int[][] t = new int[n][];
        for (int r = 0; r < n; r++) {
            t[r] = new int[r + 1];
            t[r][0] = 1;
            t[r][r] = 1;
            for (int c = 1; c < r; c++) {
                t[r][c] = t[r - 1][c - 1] + t[r - 1][c];
            }
            System.out.println(Arrays.toString(t[r]));
        }
    }
}
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

Pascal triangle in Java using array (one row only)

Going from right to left keeps the old left value safe until it is used.

public class Pascal1D {
    public static void main(String[] args) {
        int n = 5;
        int[] row = new int[n];
        for (int r = 0; r < n; r++) {
            row[r] = 1;
            for (int c = r - 1; c > 0; c--) {
                row[c] = row[c] + row[c - 1];
            }
            for (int c = 0; c <= r; c++) {
                System.out.print(row[c] + " ");
            }
            System.out.println();
        }
    }
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Pascal triangle in Java using recursion

public class PascalRecursion {
    static int value(int r, int c) {
        if (c == 0 || c == r) {
            return 1;
        }
        return value(r - 1, c - 1) + value(r - 1, c);
    }

    public static void main(String[] args) {
        for (int r = 0; r < 5; r++) {
            for (int c = 0; c <= r; c++) {
                System.out.print(value(r, c) + " ");
            }
            System.out.println();
        }
    }
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

The recursion matches the definition, but it repeats the same work many times, like recursive Fibonacci. Use it to explain the idea, not for large n.

Which Pascal triangle in Java code should you pick? Use the formula to print, the 2D array when you must keep all rows, and the 1D array when you need one row. Continue with Java coding questions or the Java full stack course.

TimeO(n^2)
SpaceO(1)
7

Review before the interview

Common mistakes

  • Dividing before multiplying in the formula, which loses the remainder.
  • Updating the 1D array from left to right, which uses a value that has already changed.
  • Using factorials in int. 13! already overflows int.
  • Printing the value after updating it, which shifts the row.

Edge cases to test

  • n = 0 prints nothing.
  • n = 1 prints only 1.
  • Two-digit values start at row 5, so use printf with a fixed width for neat centring.
  • Past the first 34 rows, int values overflow. Use long or BigInteger.

Interview follow-ups

  • How do you return only the k-th row with O(k) space?
  • How would memoization speed up the recursive version?
  • What is the sum of the numbers in row r?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us