Write a program that displays Pascal’s triangle:
Use System.out.printf to format the output into fields of width 4.
// package indefinite_loops;
import java.util.Scanner;
public class PascalTriangle {
// below method takes number of rows as parameter
public static void pascalTriangle(int rowsCount) {
for (int i = 0; i < rowsCount; i++) {
int number = 1;
System.out.printf("%" + (rowsCount - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.printf("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter rows: ");
int rows = input.nextInt();
System.out.printf("Pascal's triangle with %d rows %n \n", rows);
PascalTriangle.pascalTriangle(rows);
input.close();
}
}
Output:
enter rows:
7
Pascal's triangle with 7 rows
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1