Program to Find Transpose of 2D Matrix.

What is the Transpose of a Matrix?

A Transpose of a Matrix is obtained by changing the rows of a matrix to columns and columns to rows. Swapping the values of rows and columns (arr[i][j] with arr[j][i]).

Example:

Find Transpose of Matrix
Transpose of a Matrix

We can transpose any given array simply by running two nested loops and swapping elements of position arr[i][j] with the element of position arr[j][i]


Below is the C++ Code Implementation:

//C++ Code to Transpose a Matrix
#include<bits/stdc++.h>
using namespace std;

//function to transpose matrix
void transpose(int arr[][3]){

    for(int i = 0; i < 3; i++){
        for(int j = i+1; j < 3; j++){
            swap(arr[i][j], arr[j][i]);
        }
    }
}

int main(){
    int arr[3][3] = {{2, 3, 6},
                     {1, 4, 1},
                     {9, 2, 5}};

    transpose(arr);

    cout<<"Transpose of given Matrix: "<<endl;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }    
    return 0;             
}
Output:
Transpose of given Matrix: 
2 1 9
3 4 2
6 1 5
  • Time Complexity: O(MxN) where M is the number of rows and N is the number of columns.
  • Space Complexity: O(1), no extra space is required to solve this problem.
Next:

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS