Write a Java Program to Print Pascal Triangle using Recursion

By | 29.01.2017

Write a Java Program to Print Pascal Triangle using Recursion


Following Java Program ask to the user to enter the number of line/row upto which the Pascal’s triangle will be printed to print the Pascal’s triangle on the screen.

java-pascal-triangle

Given below is the program which uses the recursion to print Pascal’s triangle.

 

SOURCE CODE ::

 

import java.util.Scanner;

public class PascalTriangle {
    
    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of rows to print: ");
        int rows = scanner.nextInt();
        System.out.println("Pascal Triangle:");
        print(rows);
        scanner.close();
        
    }

    public static void print(int n) {
        
        for (int i = 0; i < n; i++) {
             for (int k = 0; k < n - i; k++) {
                  System.out.print(" "); // print space for triangle like structure
             }
             for (int j = 0; j <= i; j++) {
                  System.out.print(pascal(i, j) + " ");
             }
             System.out.println();
        }
    }

    public static int pascal(int i, int j) {
        if (j == 0 || j == i) {
           return 1;
        } else {
           return pascal(i - 1, j - 1) + pascal(i - 1, j);
        }
    }
}

 

OUTPUT ::

 

Enter the number of rows to print: 5
Pascal Triangle:
     1 
    1 1 
   1 2 1 
  1 3 3 1 
 1 4 6 4 1

 

3.8 5 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments