Wednesday, September 13, 2023

How to print Pascal Triangle in Java - Example Tutorial

Printing patterns with stars or numbers and triangles are some of the common programming exercises. Earlier we have seen how to print pyramid patterns with stars and today you will learn how to print Pascal's triangle in Java. Sometimes this problem is also asked as "write a program to print Pascal triangle without using array" or by just using for loop. Pascal’s triangle is a set of numbers arranged in the form of a triangle, similar to Floyd's triangle but their shape is different. Each number in the Pascal triangle row is the sum of the left number and a right number of the previous row. If a number is missing in the above row,  it is assumed to be 0. The first row starts with number 1, that's why you will see that the first two rows of the Pascal triangle just contain 1.

Here is Pascal's triangle with 6 rows, you can see it's not the number but the formatting which is difficult to code.

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

The triangle is named after the famous french mathematician Blaise Pascal who organized detailed information on the triangle in a book. However, this triangle was already known to many ancient civilizations.

Pascal’s triangle has many unique properties e.g. the sum of numbers in each row is twice the sum of numbers in the above row and the diagonals adjacent to the border diagonals contain natural numbers in order. 

Pascal triangle is also related to the Fibonacci series, if you add the numbers in Pascal's triangle in diagonal lines going up, you get one of the Fibonacci numbers.  Even though the post is about printing Pascal's triangle but a bit of history always helps.




Printing Pascal Triangle in Java

Here is the Java program to print Pascal's triangle without using an array. I have encapsulated logic inside a static method so that I can directly call it from the main method, as you might know, that you can only call the static method from the main in Java.

The method has two loops because we are printing two-dimensional patterns. The outer loop prints number of rows in the Pascal triangle and the inner loop is responsible for printing numbers in each row. The complexity of this solution is O(n^2) where n is the number of rows.

You should also pay some attention to the formatting commands we have used above to create a nicely formatted triangle. The %4d formatting instruction is used to print the number within 4 spaces. We chose 4 since we know the maximum number of digits in the largest number of a Pascal triangle with 10 rows is 3 digits.

Btw, if you want more coding problems for practice, you should check Cracking the Coding Interview, which contains more than 189 coding problems from technology companies like Google, Amazon, Facebook, Microsoft, ThoughtWorks, Apple, Twitter, and several other startups.

Java Program to print pascal triangle


If you are more interested in learning algorithms, then you should read a good book on data structure and algorithms like Introduction to Algorithm by Thomas Cormen.

Now, here is our sample program in Java to print Pascal's triangle for a given number of rows. It accepts the number of rows from the user via the command prompt. 

import java.util.Scanner;

/*
 * Java Program to print Pascal's triangle for given number of rows
 * 
 */
public class PascalTriangleInJava {

    public static void main(String[] args) {

        System.out.println("Welcome to Java program 
                   to print Pascal's triangle");
        System.out.println("Please enter number of 
                    rows of Pascal's triangle");
        
        // Using try with resource statment to open Scanner
        // no need to close Scanner later
        try (Scanner scnr = new Scanner(System.in)) {
            int rows = scnr.nextInt();            
            System.out.printf("Pascal's triangle with %d rows %n", rows);
            printPascalTriangle(rows);
        }
    }

    /**
     * Java method to print Pascal's triangle for given number of rows
     *
     * @param rows
     */
    public static void printPascalTriangle(int rows) {
        for (int i = 0; i < rows; i++) {
            int number = 1;
            System.out.printf("%" + (rows - i) * 2 + "s", "");
            for (int j = 0; j <= i; j++) {
                System.out.printf("%4d", number);
                number = number * (i - j) / (j + 1);

            }
            System.out.println();
        }
    }

}


Output
Welcome to Java program to print Pascal's triangle
Please enter number of rows of Pascal's triangle
4
Pascal's triangle with 4 rows
           1
         1   1
       1   2   1
     1   3   3   1

Welcome to Java program to print Pascal's triangle
Please enter number of rows of Pascal's triangle
7
Pascal's triangle with 7 rows
                 1
               1   1
             1   2   1
           1   3   3   1
         1   4   6   4   1
       1   5  10  10   5   1
     1   6  15  20  15   6   1



That's all about how to print Pascal's triangle in Java. As I said, it's not a difficult problem, the logic to generate numbers in each row is simple, each number is the sum of a number of its left and right in the previous row. The only tricky part is to properly format the output. In order to do that, you must know the maximum digit in the maximum number in the Pascal triangle you are printing. 

Alternatively, you can also solve the following coding problems from this blog:
  • Top 10 Programming problems from Java Interviews? (article)
  • How to calculate factorial using recursion and iteration? (solution)
  • How to find a missing number in a sorted array? (solution)
  • How to solve the FizzBuzz problem in Java? (solution)
  • How do you reverse the word of a sentence in Java? (solution)
  • How to find if the given String is a palindrome in Java? (solution)
  • How to reverse an int variable in Java? (solution)
  • Write a program to print the highest frequency word from a text file? (solution)
  • Write code to implement Bubble sort algorithm in Java? (code)
  • How to check if a given number is prime or not? (solution)
  • How to remove duplicate elements from ArrayList in Java? (solution)
  • How to check if a year is a leap year in Java? (answer)
  • Java Program to print Prime numbers up to 100 (solution)
  • Java Program to Print Alphabets in upper and lower case? (solution)
  • How do you swap two integers without using a temporary variable? (solution)
  • Write a program to check if a number is a power of two or not? (solution)
  • How to find duplicate characters from String in Java? (solution)
  • Write code to implement Quicksort algorithm in Java? (algorithm)
  • How to reverse String in Java without using StringBuffer? (solution)
  • Write a program to code insertion sort algorithm in Java (program)
This problem assumes that it will only print Pascal triangle up to 10 rows. If you want to practice more problems, see Cracking the Coding Interview book.

Thanks for reading this article. If you like then please share it with your friends and colleagues. If you have any questions or feedback, please drop a note. If you have any questions or doubt then please let us know and I'll try to find an answer for you. Btw, what is your favorite coding exercise? prime number, palindrome or this one?

3 comments:

  1. System.out.printf("%" + (rows - i) * 2 + "s", "");

    can u explain me about this line?
    please.

    ReplyDelete
  2. for i=0 & rows=5 ...it will concatenate .. "%" (5-0)*2 "s" i.e. %10s ...which gives spaces of 10 characters

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.