Tuesday, November 19, 2013

Pascal Triangle

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:

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

No comments:

Post a Comment

How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...