Thursday 9 August 2012

Pascal Triangle in Java

What is  Pascal Triangle ?


                                        Pascal triangle is triangular array of the binomial coefficent in a triangle.It is named from the name of french mathematician  Blaise Pascal.
                                         Figure shows the structure of pascal triangle having result up to six th rows.
        Pascal Triangle

//Write a Program to implement Pascal Triangle by using Java?


import java.util.*;
class Pascal
{
  public static void main(String args[])
  {
    Scanner sc=new Scanner(System.in);
    System.out.print("Enter the limit: ");
     int x=sc.nextInt();
     int arr[][]=new int [x][x];
 
    for(int i=0;i<x;i++)
    {
     for(int j=0;j<x;j++)
      {
         arr[i][0]=1;
       }
    }
 
   for(int i=1;i<x;i++)
   {
      for(int j=1;j<x;j++)
       {
         arr[i][j]=arr[i-1][j-1]+arr[i-1][j];
        }
     }
   for(int i=1;i<x;i++)
     {
      for(int j=1;j<x;j++)
       {
          if(i==j)
           arr[i][j]=1;
        }
       }
   for(int i=0;i<x;i++)
   {
     for(int k=x;k>=i;k--)
      {
        System.out.print(" ");
       }
      for(int j=0;j<=i;j++)
       {
         System.out.print(arr[i][j]+" ");
       }
      System.out.println();
    }

  }
}

Save this program as Pascal.java

Compile  Java program by using command     javac Pascal.java

Run this program by using command  java Pascal

See the Output :


If you want some more pattern code then just mail me nihalcse@gmail.com

Some more  Reference:

                                                Pascal's triangle ,|| Blaise Pascal ,|| triangular array ,||  binomial coefficients

ShareThis

Related Posts Plugin for WordPress, Blogger...