c语言数组打印杨辉三角
时间: 2023-12-03 18:40:01 浏览: 25
以下是使用C语言数组打印杨辉三角的代码示例:
```c
#include <stdio.h>
int main()
{
int arr[30][30] = {0};
int n, i, j;
printf("请输入杨辉三角的行数:");
scanf("%d", &n);
// 初始化第一列和对角线为1
for (i = 0; i < n; i++) {
arr[i][0] = 1;
arr[i][i] = 1;
}
// 计算其他元素的值
for (i = 2; i < n; i++) {
for (j = 1; j < i; j++) {
arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
}
}
// 打印杨辉三角
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
```
相关问题
c语言用数组打印杨辉三角形
以下是使用C语言数组打印杨辉三角形的代码:
```c
#include <stdio.h>
int main() {
int rows, coef = 1;
printf("请输入行数: ");
scanf("%d", &rows);
for (int i = 0; i < rows; i++) {
for (int space = 1; space <= rows - i; space++) {
printf(" ");
}
for (int j = 0; j <= i; j++) {
if (j == 0 || i == 0) {
coef = 1;
} else {
coef = coef * (i - j + 1) / j;
}
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
```
运行结果如下:
```
请输入行数: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
C语言用数组打印杨辉三角
以下是用C语言数组打印杨辉三角的代码:
```
#include <stdio.h>
int main() {
int rows, i, j, space;
printf("请输入要打印的行数:");
scanf("%d", &rows);
int triangle[rows][rows];
for (i = 0; i < rows; i++) {
for (space = 1; space < rows - i; space++) {
printf(" ");
}
for (j = 0; j <= i; j++) {
if (j == 0 || i == j) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
printf("%d ", triangle[i][j]);
}
printf("\n");
}
return 0;
}
```
运行结果:
```
请输入要打印的行数:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```