Pages

Sunday, July 23, 2017

C++ program to transpose matrix.

This C++ program will transpose given 3X3 matrix.

#include<iostream>
using namespace std;

int main()
{
 int arr[3][3], arrTrans[3][3];
 int i,j;
 //Logic for reading matrix from user...
 cout << "Enter 3 x 3 matrix:\n\n";
 for(i=0;i<3;i++)
   for(j=0;j<3;j++)
   {
    cout << "Enter element arr["<< i << "]["<< j <<"]:";
    cin >> arr[i][j];
   }  

 cout << "\nThe Original matrix is: \n";
 for(i=0;i<3;i++)
 {
  for(j=0;j<3;j++)
     cout << "\t" << arr[i][j];
  cout << endl;
 }

 cout << endl;
//Logic for transposing matrix...
 for(i=0;i<3;i++) {
  for(j=0;j<3;j++)
     arrTrans[j][i] = arr[i][j];
 }
 //Logic for printing Transposed matrix...
 printf("The transpose of the matrix is: \n");
 for(i=0;i<3;i++) {
  for(j=0;j<3;j++)
     cout << "\t" << arrTrans[i][j];
  cout << endl;
 }
 return 0;
}

Output of program

Enter 3 x 3 matrix:

Enter element arr[0][0]:1
Enter element arr[0][1]:2
Enter element arr[0][2]:3
Enter element arr[1][0]:4
Enter element arr[1][1]:5
Enter element arr[1][2]:6
Enter element arr[2][0]:7
Enter element arr[2][1]:8
Enter element arr[2][2]:9

The Original matrix is:
        1       2       3
        4       5       6
        7       8       9

The transpose of the matrix is:
        1       4       7
        2       5       8
        3       6       9

No comments:

Post a Comment