In this tutorial, we will write a java program to print Pascal Triangle.
Java Example to print Pascal’s Triangle
In this program, user is asked to enter the number of rows and based on the input, the pascal’s triangle is printed with the entered number of rows.
package com.beginnersbook; import java.util.Scanner; public class JavaExample { static int fact(int num) { int factorial; for(factorial = 1; num > 1; num--){ factorial *= num; } return factorial; } static int ncr(int n,int r) { return fact(n) / ( fact(n-r) * fact(r) ); } public static void main(String args[]){ int rows, i, j; //getting number of rows from user System.out.println("Enter number of rows:"); Scanner scanner = new Scanner(System.in); rows = scanner.nextInt(); scanner.close(); System.out.println("Pascal Triangle:"); for(i = 0; i < rows; i++) { for(j = 0; j < rows-i; j++){ System.out.print(" "); } for(j = 0; j <= i; j++){ System.out.print(" "+ncr(i, j)); } System.out.println(); } } }
Output:
Related Java examples
1. Java program to find square root of a number
2. Java program to check if a number is perfect square
3. Java program to extract digits from an input number
4. Java program to make calculator using switch case
Leave a Reply