Метод 1: использование вспомогательной матрицы
#include <iostream>
const int MAX_SIZE = 100;
void transposeMatrix(int matrix[MAX_SIZE][MAX_SIZE], int rows, int columns) {
int transpose[MAX_SIZE][MAX_SIZE];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Printing the transpose matrix
std::cout << "Transpose of the matrix:\n";
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
std::cout << transpose[i][j] << " ";
}
std::cout << "\n";
}
}
int main() {
int matrix[MAX_SIZE][MAX_SIZE];
int rows, columns;
std::cout << "Enter the number of rows in the matrix: ";
std::cin >> rows;
std::cout << "Enter the number of columns in the matrix: ";
std::cin >> columns;
std::cout << "Enter the elements of the matrix:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
std::cin >> matrix[i][j];
}
}
transposeMatrix(matrix, rows, columns);
return 0;
}
Метод 2: транспонирование на месте
#include <iostream>
const int MAX_SIZE = 100;
void transposeMatrix(int matrix[MAX_SIZE][MAX_SIZE], int rows, int columns) {
for (int i = 0; i < rows; i++) {
for (int j = i + 1; j < columns; j++) {
std::swap(matrix[i][j], matrix[j][i]);
}
}
// Printing the transpose matrix
std::cout << "Transpose of the matrix:\n";
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
}
int main() {
int matrix[MAX_SIZE][MAX_SIZE];
int rows, columns;
std::cout << "Enter the number of rows in the matrix: ";
std::cin >> rows;
std::cout << "Enter the number of columns in the matrix: ";
std::cin >> columns;
std::cout << "Enter the elements of the matrix:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
std::cin >> matrix[i][j];
}
}
transposeMatrix(matrix, rows, columns);
return 0;
}