c++ program transpose of matrix

To transpose a matrix in C++, you can follow these steps:

  1. Start by defining the size of the matrix, including the number of rows and columns.
  2. Declare a 2D array to store the elements of the matrix.
  3. Read the elements of the matrix from the user or initialize them directly in the code.
  4. Create a nested loop to iterate through the rows and columns of the matrix.
  5. Swap the elements at position (i, j) with position (j, i) to transpose the matrix. This can be done using a temporary variable.
  6. Print the transposed matrix.

Here's an example code that demonstrates the above steps:

#include <iostream>

const int MAX_SIZE = 100;

int main() {
    int matrix[MAX_SIZE][MAX_SIZE];
    int transposed[MAX_SIZE][MAX_SIZE];
    int rows, cols;

    std::cout << "Enter the number of rows: ";
    std::cin >> rows;

    std::cout << "Enter the number of columns: ";
    std::cin >> cols;

    std::cout << "Enter the elements of the matrix:\n";
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << "Enter element at position (" << i << ", " << j << "): ";
            std::cin >> matrix[i][j];
        }
    }

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

    std::cout << "The transposed matrix is:\n";
    for (int i = 0; i < cols; i++) {
        for (int j = 0; j < rows; j++) {
            std::cout << transposed[i][j] << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

This code prompts the user to enter the number of rows and columns of the matrix. Then, it asks for the elements of the matrix and stores them in the matrix array. The nested loop is used to swap the elements and store the transposed matrix in the transposed array. Finally, the transposed matrix is printed to the console.