输出8行杨辉三角形java
时间: 2023-11-24 11:59:58 浏览: 83
以下是输出8行杨辉三角形的Java代码:
```java
public class YangHuiTriangle {
public static void main(String[] args) {
int numRows = 8;
int[][] triangle = new int[numRows][numRows];
// fill the first column with 1
for (int i = 0; i < numRows; i++) {
triangle[i][0] = 1;
}
// fill the diagonal with 1
for (int i = 1; i < numRows; i++) {
triangle[i][i] = 1;
}
// fill the rest of the triangle
for (int i = 2; i < numRows; i++) {
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
// print the triangle
for (int i = 0; i < numRows; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
```
输出如下:
```
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
1 7 21 35 35 21 7 1
```
阅读全文