Transpose of a Matrix

Transpose of a Matrix in C++ (4 Programs With Output)

IntermediateTopic: Array Operations Programs
Back

C++ Transpose of a Matrix Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int rows = 3, cols = 3;
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int transpose[3][3];
    
    // Calculate transpose
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }
    
    cout << "Original matrix:" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    
    cout << "Transpose matrix:" << endl;
    for (int i = 0; i < cols; i++) {
        for (int j = 0; j < rows; j++) {
            cout << transpose[i][j] << " ";
        }
        cout << endl;
    }
    
    return 0;
}
Output
Original matrix:
1 2 3
4 5 6
7 8 9
Transpose matrix:
1 4 7
2 5 8
3 6 9

Understanding Transpose of a Matrix

This program demonstrates 4 different methods to transpose a matrix: using nested loops, in-place transpose, using functions, and using vectors. Transpose swaps rows and columns.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents