输入3 输出1 2 3 8 9 4 7 6 5 输入4 输出1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 这样的cpp程序怎么写?
时间: 2024-01-05 17:01:59 浏览: 31
你可以使用以下的C++程序来实现这个输出模式:
```cpp
#include <iostream>
void PrintSquarePattern(int n) {
int matrix[n][n];
int num = 1;
int startRow = 0, endRow = n - 1;
int startCol = 0, endCol = n - 1;
while (startRow <= endRow && startCol <= endCol) {
for (int i = startCol; i <= endCol; i++) {
matrix[startRow][i] = num++;
}
startRow++;
for (int i = startRow; i <= endRow; i++) {
matrix[i][endCol] = num++;
}
endCol--;
if (startRow <= endRow) {
for (int i = endCol; i >= startCol; i--) {
matrix[endRow][i] = num++;
}
endRow--;
}
if (startCol <= endCol) {
for (int i = endRow; i >= startRow; i--) {
matrix[i][startCol] = num++;
}
startCol++;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
int main() {
int n;
std::cout << "Enter a number: ";
std::cin >> n;
PrintSquarePattern(n);
return 0;
}
```
这个程序使用了一个二维数组来表示矩阵,并按照题目要求的输出模式填充数组。然后,使用嵌套的循环遍历数组并输出结果。你可以根据需要调整程序中的输入和输出部分来满足你的需求。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)