Java Program to Print Pascal's Triangle - The Coding Shala

Home >> Java Programs >> Print Pascal's Triangle

 In this post, we will learn how to print Pascal's triangle using the Java program.

Java Program to Print Pascal's Triangle

Write a Java program to print Pascal's triangle with the given number of rows.

Example 1:
Input: 3
Output: 
      1 
    1 1 
   1 2 1 

Solution 1

Before writing the program let's see the properties of Pascal's triangle.

  1. Every row starts with 1 and ends with 1.
  2. All the other elements in the triangle follow this rule => (arr[row][column] = arr[row-1][column] + arr[row-1][column-1]).
We can use 2D ArrayList to generate Pascal's triangle using two for loops. Time Complexity will be O(n^2).

Java Program:  

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        for(int i=0; i<numRows; i++) {
            List<Integer> temp = new ArrayList<>();
            for(int j=0; j<=i; j++) {
                if(j == 0 || j == i) {
                    // first and last element of each row
                    temp.add(1);
                } else {
                    int val = res.get(i-1).get(j) + res.get(i-1).get(j-1);
                    temp.add(val);
                }
            }
            res.add(temp);
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println("Enter number of rows for Pascal's Triangle");
        Scanner sc = new Scanner(System.in);
        int rows = sc.nextInt();
        List<List<Integer>> res = generate(rows);

        // print the triangle
        System.out.println("Pascal's Triangle with " + rows + " rows is:");
        for (int i = 0; i < rows; i++) {
            // left spacing
            for(int j = 0; j < rows-i; j++) {
                System.out.print(" ");
            }

            // print values
            for(int j = 0; j <= i; j++) {
                System.out.print(res.get(i).get(j) + " ");
            }

            System.out.println();
        }
    }
}

Output: 

Enter number of rows for Pascal's Triangle
5
Pascal's Triangle with 5 rows is:
     1 
    1 1 
   1 2 1 
  1 3 3 1 
 1 4 6 4 1 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala