Write a Java Program to Print Pascal Triangle using For Loop
To print pascal’s triangle in Java Programming, you have to use three for loops and start printing pascal’s triangle as shown in the following example.
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:
SOURCE CODE ::
import java.io.*; public class Pascal { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("\nEnter the number of rows : "); int r = Integer.parseInt(br.readLine()); for(int i=0;i<r;i++) { for(int k=r;k>i;k--) { System.out.print(" "); } int number = 1; for(int j=0;j<=i;j++) { System.out.print(number+" "); number = number * (i - j) / (j + 1); } System.out.println(); } } }
OUTPUT ::
Enter the number of rows : 6 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1