Java Program to Print Pascal Triangle using Recursion

[1038 views]


In this article we will learn how to print Pascal's Triangle based on User Input. So Program will basically ask User to enter the number of rows/lines upto which the pascal triangle will be printed and Program will display the Pascal Triangle.

Java Program for Pascal Triangle:

import java.util.Scanner; public class ScannerTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of rows: "); int rows = sc.nextInt(); System.out.println("Pascal Triangle for row: "+rows); printTriangle(rows); sc.close(); } public static void printTriangle(int n) { for (int i = 0; i < n; i++) { for (int k = 0; k < n - i; k++) { System.out.print(" "); // print space for display like triangle } 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:  5
Pascal Triangle for row: 5
     1 
    1 1 
   1 2 1 
  1 3 3 1 
 1 4 6 4 1 
        

Want to Clear Java Interview? Try our Java Interview Notes



Comments



Search
Recommended Deals










Recommended Quiz
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

    Pascal Triangle using Recursion Algorithm

    Print Pascal Triangle using Recursion based on user input