C++

A C++ Program To Find And Display A Matrix’s Transposition

In this C++ lesson, we’ll learn how to discover a matrix’s transpose. But before we run the program, let’s define what a matrix’s transpose is.
Consider the following matrix:

----------------
| 1  | 2  | 3  |
| 4  | 5  | 6  |
| 7  | 8  | 9  |
| 10 | 11 | 12 |
----------------

Below is a representation of this matrix transposed: Rows and columns are switched around; in a transposed matrix, a row from the original matrix becomes a column, and vice versa.

---------------------
| 1  | 4  | 7  | 10 |
| 2  | 5  | 8  | 11 |
| 3  | 6  | 9  | 12 |
---------------------

Let’s put this reasoning into a C++ application. You should have a fundamental understanding of arrays and multidimensional arrays in order to comprehend the program.

Using a C++ application, find a matrix’s transpose

#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

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button