matrix transpose in c++

To transpose a matrix in C++, you can use a nested loop structure. The transpose of a matrix is obtained by interchanging the rows and columns of the original matrix. Here is an example of how you can transpose a matrix in C++:

#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];

    // Transpose the matrix
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }

    // Print the transposed matrix
    for (int i = 0; i < columns; i++) {
        for (int j = 0; j < rows; j++) {
            std::cout << transpose[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

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: " << std::endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            std::cin >> matrix[i][j];
        }
    }

    std::cout << "The transposed matrix is: " << std::endl;
    transposeMatrix(matrix, rows, columns);

    return 0;
}

In this code, we first declare a constant MAX_SIZE to define the maximum size of the matrix. We then declare a function transposeMatrix that takes the matrix, number of rows, and number of columns as parameters.

Inside the transposeMatrix function, we declare a new matrix called transpose to store the transposed matrix. We use a nested loop structure to iterate through each element of the original matrix and assign it to the corresponding position in the transposed matrix.

After transposing the matrix, we use another nested loop structure to print the transposed matrix.

In the main function, we declare a matrix, the number of rows, and the number of columns. We then prompt the user to enter the elements of the matrix. Finally, we call the transposeMatrix function to transpose the matrix and print the result.

This code allows you to input the matrix dimensions and elements dynamically and then displays the transposed matrix.