java

Java Program to Print Pascal Triangle

In this tutorial, we are going to see how to write a Java program to display Pascal’s triangle. Pascal’s triangle can be constructed by first placing a 1 along the left and right edges. Then the triangle can be filled from the top by adding the two numbers just above to the left and right of each position in the triangle.


 
 

Program to Print Pascal Triangle
public class Main {
   static int factorial(int nbr) {
      int f;

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

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

Output:

        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
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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