- 2072 Chaitra · 5 marks
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)
Related questions
- Simple program illustrating OOP concept · Object Oriented Programming, chapter 1
- Compare procedural and object oriented programming · Object Oriented Programming, chapter 1
- Prime number program: procedural and OOP · Object Oriented Programming, chapter 1
- Advantages of OOP over procedural programming · Object Oriented Programming, chapter 1 · asked 5×
- How OOP differs from POP · Object Oriented Programming, chapter 1
- Concept of class with example · Object Oriented Programming, chapter 1
- Pass array; transpose 3×3 matrix · Computer Programming, chapter 7
- Transpose m×n matrix in FORTRAN · Computer Programming, chapter 11
- Object oriented system and core concepts · Object Oriented Analysis and Design, chapter 1
- Algorithmic vs object-oriented decomposition · Object Oriented Analysis and Design, chapter 1