Pascal Triangle Pattern Program in Java using For loop
ADVERTISEMENTS
Pascal triangle pattern program in java using for loop. In this article, you will learn how to make a pascal triangle pattern program in java using for loop.
Source Code
// Pascal Triangle Pattern Program in Java using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int r, co = 1, ws, i, j;
// r - denotes the number of rows
// co - denotes the coefficient value
// ws - denotes the white space
System.out.println("-----Enter the number of rows to print the pattern-----");
r = in.nextInt();
System.out.println("\n-----This is the pascal triangle pattern-----\n");
for (i = 0; i < r; i++) {
System.out.print("\t");
for (ws = 1; ws <= r - i; ws++) {
System.out.print(" ");
}
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
co = 1;
else
co = co * (i - j + 1) / j;
System.out.printf("%4d", co);
}
System.out.print("\n");
}
}
}
Output
-----Enter the number of rows to print the pattern-----
6
-----This is the pascal triangle pattern-----
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1