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.
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