用java写出一道算法题:输出一个5行的杨辉三角形。
时间: 2023-06-20 11:04:40 浏览: 86
java版杨辉三角算法
以下是Java代码,用于输出一个5行的杨辉三角形:
```
public class YangHuiTriangle {
public static void main(String[] args) {
int[][] triangle = new int[5][];
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][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
```
阅读全文