Thursday, July 12, 2012

Write a program to transpose a matrix

e.g.) Input matrix.
1  2  3
4 5 6
7 8 9

Transposed matrix.
1 4 7
2 5 8
3 6 9

C++ program to transpose a matrix

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));

    int m = 3;
    int n = 3;
    int** matrix = (int**) calloc(sizeof(int), m);
    for ( int i = 0; i < m; i++ ) {
        matrix[i] = (int*) calloc(sizeof(int), n);
    }

    // Fill random values in the matrix
    for ( int i = 0; i < m; i++ ) {
        for ( int j = 0; j < n; j++ ) {
            matrix[i][j] = rand() % 100;
        }
    }

    // Print the matrix
    for ( int i = 0; i < m; i++ ) {
        for ( int j = 0; j < n; j++ ) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    cout << endl;

    // Transpose
    for ( int i = 0; i < m; i++ ) {
        for ( int j = i + 1; j < n; j++ ) {
            int tmp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = tmp;
        }
    }

    // Print the transposed matrix
    cout << "Transposed matrix" << endl;
    for ( int i = 0; i < m; i++ ) {
        for ( int j = 0; j < n; j++ ) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    delete[] matrix;
}


Output:-
89 33 10
92 87 4
69 33 74

Transposed matrix
89 92 69
33 87 33
10 4 74

5 comments :

Contact Form

Name

Email *

Message *

Back to Top