Find and display the Transpose of a Matrix
In this C++ tutorial, we will see how to find the transpose of a matrix, before going through the program, lets understand what is the transpose of matrix. Lets say we have a matrix:
The transpose of this matrix is shown below: Rows and columns are interchanged, rows of original matrix becomes column in transpose and columns of original matrix becomes rows in transpose.
Lets implement this logic in a C++ program. To understand the program you should have a basic knowledge of arrays and multidimensional array.
C++ program to find transpose of a matrix
.
#include<iostream>
using namespace std;
int main(){
int matrix[10][10], transMatrix[10][10], row, col;
//Getting the rows from user and storing in row
cout<<"Enter the number of rows: ";
cin>>row;
//Getting the columns from user and storing in col
cout<<"Enter the number of columns: ";
cin>>col;
/* Asking the user to input the elements of matrix
* and storing them in the matrix array */
cout<<"Enter elements of matrix: "<<endl;
for(int i =0;i<row;i++) {
for(int j=0;j<col;j++) {
cin>>matrix[i][j];
} }
// Finding the transpose matrix.
for(int i=0;i<row;i++) {
for(int j=0;j<col;j++) {
transMatrix[j][i] = matrix[i][j];
} }
//Displaying the transpose matrix
cout<<"Transpose of Matrix: "<<endl;
for(int i=0;i<col;i++) {
for(int j=0;j<row;j++) {
cout<<transMatrix[i][j]<<" ";
/* This is just to format the output
* so you can see the matrix format
* in the output transpose matrix. */
if(j==row-1)
cout<<endl;
} }
return 0; }
Output
Enter the number of rows: 4
Enter the number of columns: 3
Enter elements of matrix:
1 2 3
4 5 6
7 8 9
10 11 12
Transpose of Matrix:
1 4 7 10
2 5 8 11
3 6 9 12
Leave Comment