題目:打印出楊輝三角形(要求打印出 10 行如下圖)
import java.util.Scanner;
public class WangDao {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Input the number of the rows: ");
int row = scan.nextInt();
printTriangle(row);
}
public static void printTriangle(int row) {
int[][] a = new int[row][2 * row + 1];
a[0][row] = 1;
for (int i = 1; i < row; i++) {
for (int j = row - i; j < row + i + 1; j++) {
a[i][j] = a[i-1][j-1] + a[i-1][j+1];
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < 2 * row + 1; j++) {
if (a[i][j] == 0) {
System.out.print(" ");
} else {
if (a[i][j] < row) {
System.out.print(" " + a[i][j]);
} else if (a[i][j] < row * row) {
System.out.print(" " + a[i][j]);
} else {
System.out.print(a[i][j]);
}
}
}
System.out.println();
}
}
}