Printing Pascal's Triangle in Java

Problem:

Print the shape seen below.


Solution:

public class Pyramid
{
  public static void main (String[] agrs)
  {
    int MAX = 7;
    int temp =1;
    for (int i =0;i<=MAX;i++)
    {
      temp =1;

      for (int j =MAX;j>i;j--)
      {
        System.out.print("\t");
      }
      
      for (int k =0;k<=2*(i-1)+2;k+=2)
      {
        System.out.print((temp) + "\t");
        temp+= temp;
      }
      temp/=2;

      for (int j =MAX;j>MAX;j--)
      {
        System.out.print("\t");
      }
      for (int k =0;k<=2*(i-1);k+=2)
      {
        temp/=2;
        System.out.print((temp) + "\t");
      }
      System.out.println();
    }
  }
}

No comments:

Post a Comment