C++ Transpose Matrix

C++ Transpose Matrix

Created By: Debasis Das (14-Feb-2016)

In this post we will transpose a matrix in C++

Sample Code is as follows

//  main.cpp
//  MatrixTranspose
//  Created by Debasis Das on 14/02/16.
//  Copyright © 2016 Knowstack. All rights reserved.


#include <iostream>
using namespace std;


int main(int argc, const char * argv[]) {
    int a[3][4] = {
        {0, 1, 2, 3} ,
        {4, 5, 6, 7} ,
        {8, 9, 10, 11}
    };
    
    cout <<"size of the entire array = "<< sizeof(a) << endl;
    cout <<"Size of the first row = "<< sizeof(a[0]) << endl;
    cout <<"size of the first element of the first row = " << sizeof(a[0][0])<< endl;
    
    int numOfRows = sizeof(a)/sizeof(a[0]);
    int numOfcolumns = sizeof(a[0])/sizeof(a[0][0]);

    cout <<"Number of Rows = "<< numOfRows<< endl;
    cout <<"Number of Colums = "<< numOfcolumns<< endl ;

    int i,j;
    
    cout << endl << "Matrix Before transpose: " << endl;
    for(i=0; i<numOfRows; ++i)
    for(j=0; j<numOfcolumns; ++j)
    {
        cout << " " << a[i][j];
        if(j==numOfcolumns-1)
            cout << endl << endl;
    }
    
    cout<<"We need to create an transpose array with Rows = " <<numOfcolumns << " & Number of Columns = " << numOfRows <<endl;

    int transposedMatrix[numOfcolumns][numOfRows];
    
    
    for(i=0; i<numOfRows; ++i)
    for(j=0; j<numOfcolumns; ++j)
    {
        transposedMatrix[j][i]=a[i][j];
    }

     //Displaying the transpose
        cout << endl << "Transpose of Matrix: " << endl;
        for(i=0; i<numOfcolumns; ++i)
            for(j=0; j<numOfRows; ++j)
            {
                cout << " " << transposedMatrix[i][j];
                if(j==numOfRows-1)
                    cout << endl << endl;
            }
        return 0;
}

Output of Sample Code

size of the entire array = 48
Size of the first row = 16
size of the first element of the first row = 4
Number of Rows = 3
Number of Colums = 4

Matrix Before transpose: 
 0 1 2 3

 4 5 6 7

 8 9 10 11

We need to create an transpose array with Rows = 4 & Number of Columns = 3

Transpose of Matrix: 
 0 4 8

 1 5 9

 2 6 10

 3 7 11

Program ended with exit code: 0
Posted in C++

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news