Saturday 28 October 2017

Pascal triangle in java

Program: Write a program to enter number of rows and create a Pascal Triangle.
Input: 5
Output:
     1               row=1
    1 1              row=2
   1 2 1             row=3
  1 3 3 1            row=4
 1 4 6 4 1           row=5



Source FilePascalTriangle.java

package triangle;

public class PascalTriangle
{
      public static void main(String args[])
      {
            int rows, i, k, number=1, j;
            rows = 5;  //change number of rows as per need

            for(i=0;i<rows;i++)
            {
                  for(k=rows; k>i; k--)
                  {
                        System.out.print(" ");
                  }
                  number = 1;
                  for(j=0;j<=i;j++)
                  {
                        System.out.print(number+ " ");
                        number = number * (i - j) / (j + 1);
                  }
                  System.out.println();
            }
      }
}



OUTPUT:

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




 You may also like to read about:

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.