Java Program to display Pascal's Triangle up to a number of rows

Pascal triangle java program
Code Here:
import java.util.*;
class PascalTriangle
{
  public static void main(String args[])
  {
    Scanner rd = new Scanner(System.in);
    int i,j,n,k,p=10;
    int m[] = new int[20];
    System.out.print("Enter the number of rows:");
    n = rd.nextInt();
    m[0] =1;
    for(i=0;i<n;i++)
    {
      for(k=p;k>=1;k--)
      System.out.print(" ");
      for(j=0;j<=i;j++)
      System.out.print(m[j]+" ");
      System.out.println();
      p--;
      for(j=i+1;j>0;j--)
      m[j] = m[j] + m[j - 1];
    }
  }
}

Output:1

Enter the number of rows:3
          1
         1 1
        1 2 1

Output:2

Enter the number of rows:5
            1
          1  1
         1 2 1
        1 3 3 1
       1 4 6 4 1

Post a Comment

0 Comments