二维数组C语言实现杨辉三角
时间: 2024-01-06 18:57:25 浏览: 52
下面是一个C语言程序,用二维数组实现杨辉三角:
```c
#include <stdio.h>
int main() {
int n, i, j;
printf("Enter the number of rows: ");
scanf("%d", &n);
int arr[n][n];
// 初始化数组
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
if (j == 0 || j == i) {
arr[i][j] = 1;
} else {
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;
}
```
在程序中,我们首先读取输入的行数n,然后创建一个n行n列的二维数组arr。接下来,我们使用两个嵌套的循环来初始化数组,每个元素的值都是它上方两个元素的和。最后,我们再次使用两个嵌套的循环来输出杨辉三角的值。
相关问题
用c语言二维数组实现输出杨辉三角形
好的,以下是用 C 语言二维数组实现输出杨辉三角形的代码:
```c
#include <stdio.h>
int main() {
int rows, coef = 1;
printf("Enter the number of rows: ");
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;
}
```
这个程序先让用户输入要输出的杨辉三角形的行数。然后,它使用两个嵌套的 for 循环来遍历二维数组并计算每个元素的值。内部循环计算组合系数,并使用 printf 函数打印它。外部循环控制打印每行的元素。
c语言用二维数组遍写杨辉三角
#include <stdio.h>
int main()
{
int rows, coef = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
int triangle[rows][rows];
for(int i = 0; i < rows; i++)
{
for(int j = 0; j <= i; j++)
{
if(j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
triangle[i][j] = coef;
}
}
for(int i = 0; i < rows; i++)
{
for(int j = 0; j <= i; j++)
{
printf("%d ", triangle[i][j]);
}
printf("\n");
}
return 0;
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)