Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Pascal’s triangle is an arrangement of binomial coefficients in triangular form. The numbers of Pascal’s triangle are arranged so that each is the sum of the two numbers immediately above it.

In this tutorial, we’ll see how to print Pascal’s triangle in Java.

2. Use Recursion

We can print Pascal’s triangle using recursion with the formula nCr: n ! / ( ( n – r ) ! r ! )

First, let’s create a recursive function:

public int factorial(int i) {
    if (i == 0) {
        return 1;
    }
    return i * factorial(i - 1);
}

Then we can print the triangle using that function:

private void printUseRecursion(int n) {
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n - i; j++) {
            System.out.print(" ");
        }

        for (int k = 0; k <= i; k++) {
            System.out.print(" " + factorial(i) / (factorial(i - k) * factorial(k)));
        }

        System.out.println();
    }
}

The result with n = 5 will look like this:

       1
      1 1
     1 2 1
    1 3 3 1
   1 4 6 4 1
  1 5 10 10 5 1

3. Avoid Using Recursion

Another way to print Pascal’s triangle without recursion is to use binomial expansion.

We always have the value 1 at the beginning of each line, then the value of k at the (n) line and the (i) position will be calculated as:

k = ( k * (n - i) / i ) 

Let’s create our function using this formula:

public void printUseBinomialExpansion(int n) {
    for (int line = 1; line <= n; line++) {
        for (int j = 0; j <= n - line; j++) {
            System.out.print(" ");
        }

        int k = 1;
        for (int i = 1; i <= line; i++) {
            System.out.print(k + " ");
            k = k * (line - i) / i;
        }

        System.out.println();
    }
}

4. Conclusion

In this quick tutorial, we’ve learned two ways to print Pascal’s triangle in Java.

The example code from this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.