Pascal Triangle in Java

You are currently viewing Pascal Triangle in Java

In this article, I’m going to share the details about the pascal triangle in java program. Basically, We need to know about the pascal triangle and how to perform a task using the java program? Shall we start the discussion? Let’s go.

What is the pascal triangle?

A triangular array of the binomial coefficients is called the Pascal triangle. It can be used in the binomial expansion of a polynomial, in probability, to find the number of combinations, and also find the Fibonacci series.

Pascal Triangle in Java

We can use the for loop to perform a task in the below program.

public class PascalsTriangle {
   static int factorial(int n) {
      int f;

      for(f = 1; n > 1; n--){
         f *= n;
      }
      return f;
   }
   static int ncr(int n,int r) {
      return factorial(n) / ( factorial(n-r) * factorial(r) );
   }
   public static void main(String args[]){
      System.out.println();
      int n, i, j;
      n = 5;

      for(i = 0; i <= n; i++) {
         for(j = 0; j <= n-i; j++){
            System.out.print(" ");
         }
         for(j = 0; j <= i; j++){
            System.out.print(" "+ncr(i, j));
         }
         System.out.println();
      }
   }
}

Program Execution

Initially, The respective variables will store the input rows and the columns. The number of rows and the number of elements will help to draw the pascal triangle here.

After that, The for loop will use to create inner and outer iteration based on the “i” and “j” to print rows. Later, We will print blank space and close the inner loop.

In addition, We will create an inner iteration for “j” to “i” and print nCr to “i” and “j”. At last, We will close the inner loop. The “n/” function will use to print the new line for each iteration.

Finally, The pascal triangle output will display on the result screen using the system.out.printIn() function.

Read Also : Java Program to Check Leap Year

Note

If you want to know the concepts of Pascal Triangle in JavaScript and Pascal Triangle in PHP then please read those articles which we have already shared on our webpage.

Output

The output will provide below for your reference.

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

Final Words

I hope this program about Pascal Triangle in Java will be useful to you. If you face any difficulty in this article means let me know via the comment section. Share this program with other Java developers via social media. Thank You!

Manoj S

Hi, I'm Manoj working as a part-time blogger in Coding Diksha. Here, I post about programming to help developers.

Leave a Reply