Home »
C++ Programs
C++ program to find transpose of a matrix using class
Submitted by Shubh Pachori, on August 08, 2022
Problem statement
Given matrix, we have to transpose it using the class and object approach.
Example:
Input:
Enter Matrix:
Enter x[0][0] : 1
Enter x[0][1] : 2
Enter x[1][0] : 3
Enter x[1][1] : 4
Matrix:
1 2
3 4
Output:
Transpose of matrix
1 3
2 4
C++ Code to find transpose of a matrix using class and object approach
#include <iostream>
using namespace std;
// create a class
class Matrix {
// private data members
private:
int x[10][10];
int row, col;
// public functions
public:
// getMatrix() function to insert matrix
void getMatrix(int r, int c) {
// initialising a matrix type variable
Matrix M1;
// copying value of parameters in the data members
row = r;
col = c;
// nested for loop for insertion of matrix
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << "Enter x[" << i << "][" << j << "] : ";
cin >> x[i][j];
}
}
}
// putMatrix() function to print the matrix
void putMatrix() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << x[i][j] << " ";
}
cout << "\n";
}
}
// transpose() function to perform transpose the matrix
Matrix transpose() {
// initialising a Matrix type variable
Matrix M;
// copying the value of parameters in the data members
M.row = row;
M.col = col;
// nested for loop to transpose the matrix
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
M.x[j][i] = x[i][j];
}
}
// returning the resulted matrix
return (M);
}
};
int main() {
// creating objects
Matrix M1, M2;
// inserting matrix using getMatrix() function
cout << "Enter Matrix:\n" << endl;
M1.getMatrix(2, 2);
// printing the matrix using putMatrix() function
cout << "\nMatrix:" << endl;
M1.putMatrix();
cout << endl;
// calling transpose() function to transpose the matrix
M2 = M1.transpose();
cout << "\nTranspose of matrix\n" << endl;
// printing the resulted matrix
M2.putMatrix();
return 0;
}
Output
Enter Matrix:
Enter x[0][0] : 33
Enter x[0][1] : 22
Enter x[1][0] : 11
Enter x[1][1] : 44
Matrix:
33 22
11 44
Transpose of matrix
33 11
22 44
Explanation
In the above code, we have created a class Matrix, three int type data members x[10][10], row and col to store the matrix, row and column, and public member functions getMatrix(), putMatrix() and transpose() to insert, print and transpose the matrix.
In the main() function, we are creating an object M1 and M2 of class Matrix, reading matrices given by the user using getMatrix() function, and finally calling the transpose() member function to transpose the given matrix. The transpose() function contains the logic to transpose the given matrix and printing the result.
C++ Class and Object Programs (Set 2) »