用C语言如何输出回型矩阵
时间: 2024-06-12 20:10:59 浏览: 107
可以使用双重循环来输出回型矩阵,具体代码如下:
```
#include <stdio.h>
int main() {
int n;
printf("请输入矩阵的大小:");
scanf("%d", &n);
int matrix[n][n];
int num = 1;
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
for (int i = top + 1; i <= bottom; i++) {
matrix[i][right] = num++;
}
if (left < right && top < bottom) {
for (int i = right - 1; i >= left; i--) {
matrix[bottom][i] = num++;
}
for (int i = bottom - 1; i > top; i--) {
matrix[i][left] = num++;
}
}
left++;
right--;
top++;
bottom--;
}
printf("回型矩阵如下:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
```
阅读全文