In this tutorial, we will write a program to print pascal triangle in java. Before that, you should have knowledge on the following topic in Java.
Pascal’s triangle is one of the important examples that is taught to the student. The number outside Pascal’s triangle is zero (0), which is not visible. It is a pattern where the triangle starts from 1 at the top and below is the addition of the upper level as you can see in the figure below. The addition continues until the required level is reached.
Java Program to Print Pascal Triangle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | //Print Pascal Triangle in java import java.util.Scanner; public class Main { public static void main(String args[]) { int n, i, j, k, num = 1; Scanner sc = new Scanner(System.in); System.out.print("Enter the no. of rows: "); n = sc.nextInt(); for (i = 0; i < n; i++) { for (k = n; k > i; k--) { System.out.print(" "); } num = 1; for (j = 0; j <= i; j++) { System.out.print(num + " "); num = num *(i - j) / (j + 1); } System.out.println(); } } } |
Output: