Pascal’s triangle in java using recursion

Let’s learn pascal’s triangle in java using recursion.

Pascal’s triangle in java using recursion

Here’s program to print pascal’s triangle using recursion.

import java.util.Scanner;
public class RecursionPascalTriangle 
{
   public static void display(int num)
   {
      for(int a = 0; a < num; a++)
      {
         for(int b = 0; b <= a; b++)
         {
            System.out.println(pascalTriangle(a, b) + " ");
         }
         System.out.println();
      }
   }
   public static int pascalTriangle(int a, int b)
   {
      if(b == 0 || b == a)
      {
         return 1;
      }
      else
      {
         return pascalTriangle(a - 1, b - 1) + pascalTriangle(a - 1, b);
      }
   }
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of rows: ");
      int row = sc.nextInt();
      display(row);
      sc.close();
   }
}


Output:

Please enter number of rows: 8

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
1 7 21 35 35 21 7 1


Also read – HashSet in java