C语言 Give a positive integer n not greater than 9 and output a “Snake matrix” with n rows and n columns. For example: Input: 4 output:
时间: 2024-03-26 11:34:06 浏览: 61
Sure, here is the C code that generates a Snake matrix with n rows and n columns for a positive integer n not greater than 9:
```
#include <stdio.h>
int main() {
int n, i, j, num = 1;
int matrix[9][9] = {0};
printf("Enter a positive integer not greater than 9: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
if (i % 2 == 0) {
for (j = 0; j < n; j++) {
matrix[i][j] = num;
num++;
}
} else {
for (j = n - 1; j >= 0; j--) {
matrix[i][j] = num;
num++;
}
}
}
printf("The Snake matrix is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
```
This code prompts the user to enter a positive integer not greater than 9, creates an empty matrix of size n x n, and then fills in the matrix in a "snake" pattern by iterating over each row and column. Finally, it prints the matrix to the console.
For example, if the user enters 4, the output will be:
```
The Snake matrix is:
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
```
I hope this helps! Let me know if you have any other questions.
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)