Java Program to Print Pascal Triangle using Recursion

[9282 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 
                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?



Comments










Search

Hot Deals ends in













Technical Quizzes Specially For You:

Games:
     



Search Tags

    Pascal Triangle using Recursion Algorithm

    Print Pascal Triangle using Recursion based on user input