顺时针打印出一个行列相同n阶矩阵,传入参数为矩阵阶数(整数n)。使用C语言实现)
时间: 2023-12-10 14:37:16 浏览: 39
以下是使用C语言实现的顺时针打印n阶矩阵的代码:
```c
#include <stdio.h>
void printMatrix(int n, int matrix[][n]) {
int row_start = 0, row_end = n-1;
int col_start = 0, col_end = n-1;
int i, j;
while (row_start <= row_end && col_start <= col_end) {
for (i = col_start; i <= col_end; i++) {
printf("%d ", matrix[row_start][i]);
}
row_start++;
for (i = row_start; i <= row_end; i++) {
printf("%d ", matrix[i][col_end]);
}
col_end--;
if (row_start <= row_end) {
for (i = col_end; i >= col_start; i--) {
printf("%d ", matrix[row_end][i]);
}
row_end--;
}
if (col_start <= col_end) {
for (i = row_end; i >= row_start; i--) {
printf("%d ", matrix[i][col_start]);
}
col_start++;
}
}
}
int main() {
int n, i, j;
printf("请输入矩阵的阶数:");
scanf("%d", &n);
int matrix[n][n];
printf("请输入矩阵元素:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("顺时针打印矩阵:\n");
printMatrix(n, matrix);
return 0;
}
```
在这段代码中,我们使用了一个while循环来不断打印矩阵,每次循环打印一个方向。在每个方向上,我们使用for循环来遍历矩阵,并使用printf函数打印矩阵元素。同时,我们用四个变量来记录矩阵四个边界的位置,以控制打印的方向。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)