Menu Close

Matrix Transpose – C++

The program prompts the user to enter the number of rows and columns for the matrix. It then takes user input for the elements of the matrix.

The program performs matrix transposition in-place by swapping the elements across the main diagonal.

Finally, it displays the transposed matrix.

				
					#include <iostream>
using namespace std;

int main() {
    int rows, cols;

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

    int matrix[rows][cols];

    cout << "Enter elements of the matrix:" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cin >> matrix[i][j];
        }
    }

    // Transpose the matrix in-place
    for (int i = 0; i < rows; i++) {
        for (int j = i + 1; j < cols; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }

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

    return 0;
}

				
			

Output


Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the matrix:
1
2
3 
4
Transposed matrix:
1 2 
3 4 

More Related Stuff