Java Program to Print Pascal Triangle

  • Write a java program to print pascal triangle till N rows.

In this java program, we have to print the pascal triangle on screen till N rows. We will take number of rows as input from user. Before jumping into java program, here is the brief introduction of pascal triangle.

For Example : pascal triangle of 5 rows.
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

Pascal Triangle is an isosceles triangle of binomial coefficients. Nth row of pascal triangle contains N binomial coefficients. Here is the formula to find the value of nth element of rth row of pascal triangle.

Pascal triangle formula

Java program to print pascal triangle

In this java program, we first take number of rows as input from user and store it in variable "rows". Here we are using nested for loops to print pascal triangle. One iteration of outer for loop will print one row of pascal triangle. Inside the body of outer for loop we have two inner for loop, first for loop will print the spaces and second for loop will print the binomial coefficients of current row by using "getFactorial" function.

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to print pascal triangle
 */
public class PascalTriangle {
    public static void main(String args[]) {
        int row, rows, i, num;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Number of Rows in Pascal Triangle");
        rows = scanner.nextInt();

        // Print Pascal Triangle
        for (row = 0; row < rows; row++) {
            // Print Spaces for every row
            for (i = row; i <= rows; i++)
                System.out.print("  ");

            for (i = 0; i <= row; i++) {
                num = getFactorial(row) / (getFactorial(i) * getFactorial(row - i));
                System.out.print("  " + num);
            }
            System.out.print("\n");
        }
    }

    /**
     * Returns the factorial of N
     */
    public static int getFactorial(int N) {
        if (N < 0) {
            // Invalid input
            return -1;
        }

        int nFactorial = 1, i;
        // N! = N*(N-1)*(N-2)*(N-3)*.....*3*2*1
        for (i = 1; i <= N; i++) {
            nFactorial = nFactorial * i;
        }
        return nFactorial;
    }
}
Output
Enter Number of Rows in Pascal Triangle
5
              1
            1  1
          1  2  1
        1  3  3  1
      1  4  6  4  1