Q:

Write a Java Program to Print Pascal Triangle using Recursion

belongs to collection: Java Basic Solved Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Solved Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a Java Program to Perform Mathematical Opera... >>
<< Write a Java Program to Print Floyd’s Triangle u...