C++ Program to Transpose a Matrix

1. Introduction

The transpose of a matrix is obtained by switching its rows with columns. It's an essential operation in linear algebra and finds its applications in various fields including computer graphics, statistics, and more. In this blog post, we'll explore a C++ program that transposes a matrix.

2. Program Overview

1. The user is prompted to provide dimensions and elements of the matrix.

2. The program initializes a new matrix to hold the transposed result.

3. It then uses nested loops to switch rows with columns.

4. Finally, the transposed matrix is displayed.

3. Code Program

#include <iostream>
using namespace std;

int main() {
    int r, c;

    // Get matrix dimensions from user
    cout << "Enter rows and columns for matrix: ";
    cin >> r >> c;

    double m[r][c], transpose[c][r];

    // Get matrix elements from user
    cout << "Enter elements of matrix:" << endl;
    for(int i=0; i<r; ++i)
        for(int j=0; j<c; ++j)
            cin >> m[i][j];

    // Compute transpose of matrix
    for(int i=0; i<r; ++i)
        for(int j=0; j<c; ++j)
            transpose[j][i] = m[i][j];

    // Display transposed matrix
    cout << "Transposed Matrix:" << endl;
    for(int i=0; i<c; ++i) {
        for(int j=0; j<r; ++j)
            cout << transpose[i][j] << " ";
        cout << endl;

    return 0;


For 2x2:
Enter rows and columns for matrix: 2 2
Enter elements of matrix:
1 2 
3 4
Transposed Matrix:
1 3 
2 4 

For 3x3:

Enter rows and columns for matrix: 3 3
Enter elements of matrix:
1 2 3
4 5 6
7 8 9
Transposed Matrix:
1 4 7 
2 5 8 
3 6 9 

4. Step By Step Explanation

1. Matrix Input: The program starts by taking the dimensions of the matrix followed by its individual elements.

2. Transposing Operation: The essence of matrix transposition lies in switching the rows and columns. This is achieved using nested loops, where the element at the i-th row and j-th column in the original matrix is placed at the j-th row and i-th column in the transposed matrix.

3. Result Display: The program then outputs the transposed matrix.

By understanding this program, you get to grasp not only the logic behind matrix transposition in programming but also gain insights into manipulating two-dimensional arrays in C++.