How to find transpose of a matrix in C++

In this tutorial, we will learn how to find the transpose of a matrix in C++ and will understand the logic behind the program.

Transpose of a matrix is a manipulation of a matrix such that each row becomes column and each column becomes a row of that matrix. In other words, Transpose of a matrix M[][] is when M[i][j] becomes M[j][i].

We can transpose a matrix if and only if the matrix is a square matrix, i.e., if the matrix has the same rows and columns size/length.

Example:

Consider a matrix of 4x4
Input matrix: 
                1  4  5  6   
                2  3  5  4  
                4  6  8  7 
                1  4  8  0

Transpose of this matrix will be:

                1  2  4  1
                4  3  6  4
                5  5  8  8
                6  4  7  0

Algorithm

  1. Declare two matrices say ‘A‘ and ‘B’ of size m*n and initialize the first matrix ‘A’. (where n and m are the lengths of row and column respectively)
  2. check whether ‘n‘ is equal to ‘m‘. Then proceed for next steps.
  3. Print the Matrix befor transpose.
  4. start a loop form i = 0 to ‘n’
    a. start another loop form j = 0 to ‘n’
    i) perform transpose of matrix by B[i][j] = A[j][i].
    ii) increse ‘j’ by one.
    b. increse ‘i’ by one.
  5. print the elements second matrix ‘B’.

The implementation of the algorithm in C++ as follows:

transpose of a matrix in C++

 

#include <cstdlib>
#include <iostream>
#define size 100
using namespace std;

//Funtion to diaplay elements of a matrix
void display(int Matrix[size][size], int n, int m){
    
    for(int i = 0;i < n; i++){
        for(int j = 0;j < m;j++){
            cout<<Matrix[i][j]<<" ";
        }
        cout<<endl;
    }
}

int main(int argc, char** argv) {
    int A[size][size],B[size][size], n, m;
    
    cout<<"Enter the length of rows: ";
    cin>>n;                             
    cout<<"Enter length of column: ";
    cin>>m;
    
    //checking for equality of m and n
    if(n != m){
        cout<<"Length of rows and columns must be equal.";
        exit(0);
    }
    
    //Taking input in matrix 
    cout<<"\nEnter the elements of matrix: \n";
    for(int i = 0;i < n; i++){
        for(int j = 0;j < m;j++){
            cin>>A[i][j];
        }
    }
    
    cout<<"\nMatrix, before transpose: \n"<<endl;
    display(A, n, m);         
    
    //Transpose of matrix
    for(int i = 0;i < n; i++){
        for(int j = 0;j < m;j++){
            B[i][j] = A[j][i];
        }
    }
    
    cout<<"\nMatrix after transpose: \n"<<endl;
     display(B, n, m);
     
    return 0;
}

Time complexity: O(n^2)




you may also learn: 

  1. Addition of two matrices in C++
  2. Find sum of each row and column of a matrix in C++
  3. Print the corner elements of the matrix using C++


Leave a Reply

Your email address will not be published. Required fields are marked *