3*3二维数组行列互换c++
时间: 2023-06-16 22:06:43 浏览: 102
C语言将给定的3× 3的整型数组转置(行列互换)。
可以通过以下代码实现二维数组的行列互换:
```c++
#include <iostream>
using namespace std;
const int ROWS = 3;
const int COLS = 3;
int main()
{
int arr[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// 输出原始数组
cout << "Original array:" << endl;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
// 二维数组行列互换
int temp;
for (int i = 0; i < ROWS; i++) {
for (int j = i; j < COLS; j++) {
temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
// 输出行列互换后的数组
cout << "After transpose:" << endl;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果为:
```
Original array:
1 2 3
4 5 6
7 8 9
After transpose:
1 4 7
2 5 8
3 6 9
```
阅读全文