Give a positive integer n not greater than 9 and output a “Snake matrix” with n rows and n columns. c语言
时间: 2024-03-26 11:37:37 浏览: 97
以下是以 C 语言实现的 “Snake matrix” 代码:
```c
#include <stdio.h>
int main() {
int n, i, j, counter = 1;
printf("Please enter a positive integer n not greater than 9: ");
scanf("%d", &n);
int matrix[n][n];
for (i = 0; i < n; i++) {
if (i % 2 == 0) { // even rows
for (j = 0; j < n; j++) {
matrix[i][j] = counter;
counter++;
}
} else { // odd rows
for (j = n - 1; j >= 0; j--) {
matrix[i][j] = counter;
counter++;
}
}
}
// print the matrix
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
```
运行程序后,输入一个不大于 9 的正整数 n,即可输出一个 n 行 n 列的 “Snake matrix”。其中,偶数行从左到右填充,奇数行从右到左填充。
阅读全文