Pascal triangle program in java without using arrays

Let’s learn pascal triangle program in java without using arrays.

Pascal triangle program in java without using arrays

To write a program to print pascal triangle without using array we are using two for loops.

Outer for loop print number of rows and inner for loop prints numbers in each rows.

Here’s java program.

import java.util.Scanner;
public class PascalTriangleDemo 
{
   public static void main(String[] args) 
   {
      System.out.println("Please enter number of rows to print pascal's triangle: ");
      Scanner sc = new Scanner(System.in);
      int row = sc.nextInt();            
      System.out.println("Pascal's triangle with " + row + " rows.");
      displayPascalTriangle(row);
      sc.close();
   }
   public static void displayPascalTriangle(int r) 
   {
      for(int a = 0; a < r; a++) 
      {
         int num = 1;
         System.out.printf("%" + (r - a) * 2 + "s", "");
         for(int b = 0; b <= a; b++) 
         {
            System.out.printf("%4d", num);
            num = num * (a - b) / (b + 1);
         }
         System.out.println();
      }
   }
}


Output:

Please enter number of rows to print pascal’s triangle: 5
Pascal’s triangle with 5 rows
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Please enter number of rows to print pascal’s triangle: 7
Pascal’s triangle with 7 rows
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