C 语言实现螺旋矩阵输出199


螺旋矩阵是一种特殊的矩阵,其中元素以特定模式排列,形成一个螺旋形。在 C 语言中,我们可以使用循环和条件语句来实现螺旋矩阵的输出。

下面是一个 C 语言程序,它可以输出一个 n×n 的螺旋矩阵,其中 n 是用户输入的整数:```c
#include
int main() {
int n;
printf("Enter the size of the matrix: ");
scanf("%d", &n);
int matrix[n][n];
// Initialize the matrix with zeros
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = 0;
}
}
int row = 0, col = 0;
int direction = 0; // 0: right, 1: down, 2: left, 3: up
int count = 1;
// Loop until all elements are filled
while (count = 0 && matrix[row][col - 1] == 0) {
col--;
} else {
direction = 3;
row--;
}
break;
case 3: // up
if (row - 1 >= 0 && matrix[row - 1][col] == 0) {
row--;
} else {
direction = 0;
col++;
}
break;
}
// Increment the count
count++;
}
// Print the spiral matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("");
}
return 0;
}
```

这个程序首先提示用户输入矩阵的大小。然后,它初始化一个 n×n 的矩阵,将其所有元素设置为 0。

使用四个变量(row、col、direction 和 count)来跟踪螺旋输出的过程。direction 变量指示当前的输出方向,count 变量跟踪已输出的元素数量。

while 循环持续输出元素,直到所有元素都被填充。在循环中,程序填充当前单元格,然后根据当前方向确定下一个方向。当达到矩阵的边界或当前单元格已被填充时,程序会更新方向。

当所有元素都被填充后,程序会打印螺旋矩阵。该代码使用嵌套 for 循环遍历矩阵并打印每个元素。

这个程序可以用来生成任何大小的螺旋矩阵,并输出结果。

2025-02-03


上一篇:**C 语言中的强制函数值清除**

下一篇:在 C 语言中使用 `rename()` 函数修改文件名