Print Pascal Triangle in Java

Programming is always a fun and creative task. The more creative you can think the better programmer you will become. However, programming isn’t always about solving problems sometimes there’s also a fun aspect to it which makes it way more satisfying. If you are a programmer then you might have already played with patterns, strings, etc multiple times.

Well, it’s also likely that you are already familiar with printing triangle patterns. So in today’s article, we will create a program to Print Pascal Triangle in Java. With the help of this program, you will be able to print an amazing looking Triangle of integers using java language. Practising these types of questions also helps to get an upper edge in Competitive Programming.

So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a somewhat tricky question you might get asked in an interview so make sure to practice it on your own after reading this article.

 

Also Read: How To Run Java in Visual Studio Code on Windows 10

 

What’s The Approach?

 

We’re going to follow the  Binomial Coefficient approach to print this triangle pattern.

 

So the key concept here is that every ‘A’th value in a line number is Binomial Coefficient C(line, a). And all lines start with starting value 1.

 

Therefore we are going to use the formula C(line, i) = C(line, i-1) * (line – i + 1) / i in our program. 

 

Java Program To Print Pascal Triangle

 

// Java Program to Print Pascal's Triangle

// Importing input output classes
import java.io.*;

// Main Class
public class TechDecodeTutorials {

    // Pascal function
    public static void printPascal(int k)
    {
        for (int line = 1; line <= k; line++) {
            for (int b = 0; b <= k - line; b++) {

                // Print whitespace for left spacing
                System.out.print(" ");
            }

            // Variable used to represent C(line, i)
            int C = 1;

            for (int a = 1; a <= line; a++) {

                // The first value in a line is always 1
                System.out.print(C + " ");
            
                C = C * (line - a) / a;
            }

            // By now, we are done with one row so
            // a new line is required
            System.out.println();
        }
    }

    // Main driver method
    public static void main(String[] args)
    {
        // Declare and initialize variable number
        // uoto which Pascal's triangle is required on
        // console
        int n = 6;

        // Calling the Pascal function(Method 1)
        printPascal(n);
    }
}

 

Output:

 

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

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *