Software & Finance





Java - Pascal Triangle





Here is the Java source code for Pascal Triangle is given below:

 

Source Code


import java.io.*;

import java.lang.*;

 

 

class PascalTriangle { 

 

    public static void main(String[] args) {

 

            String inpstring = "";

            InputStreamReader input = new InputStreamReader(System.in);

            BufferedReader reader = new BufferedReader(input);

 

            try

            {

                  System.out.print("Enter number of rows for pascal triangle:");

                  inpstring = reader.readLine();

                  int n = Integer.parseInt(inpstring, 10);

 

                  for (int y = 0; y < n; y++)

                  {

                        int c = 1;

 

                        for(int q = 0; q < n - y; q++)

                        {

                              System.out.print("   ");

                        }

 

                        for(int x = 0; x <= y; x++)

                        {

                              System.out.print("   ");

                              System.out.print(c); // 3 digits

                              System.out.print(" ");

                              c = c * (y - x) / (x + 1);

                        }

 

                        System.out.println();

                        System.out.println();

                  }

                 

                  System.out.println();

            }

            catch (Exception e)

            {

                  e.printStackTrace();

            }

    }

}

 

 

Output


 

D:\Program Files\Java\jdk1.6.0_23\bin>Java PascalTriangle

Enter number of rows for pascal triangle:6

                     1

 

                  1    1

 

               1    2    1

 

            1    3    3    1

 

         1    4    6    4    1

 

      1    5    10    10    5    1

 

 

D:\Program Files\Java\jdk1.6.0_23\bin>Java PascalTriangle

Enter number of rows for pascal triangle:9

                              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

 

         1    7    21    35    35    21    7    1

 

      1    8    28    56    70    56    28    8    1