Skip to main content

Transpose of matrix using OOP

Short answer

Encapsulate the matrix in a class Matrix with read() and display(). The transpose() method creates a new Matrix with swapped rows/cols and assigns t[j][i] = a[i][j], then returns the transposed object.

Write a program to find the transpose of given Matrix using the concept of Object Oriented Programming.

The matrix and the operations on it are placed in a class Matrix. The transpose of an r × c matrix is a c × r matrix where t[j][i] = a[i][j].

#include <iostream>
using namespace std;

class Matrix {
    int a[10][10];
    int r, c;
public:
    void read() {
        cout << "Enter rows and columns: ";
        cin >> r >> c;
        cout << "Enter elements:" << endl;
        for (int i = 0; i < r; i++)
            for (int j = 0; j < c; j++)
                cin >> a[i][j];
    }
    Matrix transpose() {
        Matrix t;
        t.r = c;                    // rows and columns swap
        t.c = r;
        for (int i = 0; i < r; i++)
            for (int j = 0; j < c; j++)
                t.a[j][i] = a[i][j];
        return t;
    }
    void display() {
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++)
                cout << a[i][j] << "\t";
            cout << endl;
        }
    }
};

int main() {
    Matrix m, t;
    m.read();
    cout << "Original matrix:" << endl;
    m.display();
    t = m.transpose();
    cout << "Transpose:" << endl;
    t.display();
    return 0;
}

Sample run (2 × 3 matrix)

Original matrix:
1   2   3
4   5   6
Transpose:
1   4
2   5
3   6

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 1 questions →