C++ Program to Transpose a Matrix

Write a C++ Program to Transpose a Matrix with an example. Within the C++ nested for loop, we assigned the original matrix row column value to the column row position. Next, we used another nested for loop to print the transposed matrix output.

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns;
	
	cout << "\nPlease Enter the rows and Columns of Matrix to Transpose =  ";
	cin >> i >> j;
	
	int orgMat[i][j], transMat[i][j];
	
	cout << "\nPlease Enter the Original Matrix Items\n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < i; columns++) {
			cin >> orgMat[rows][columns];
		}	
	}	
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < j; columns++) {
			transMat[columns][rows] = orgMat[rows][columns];
		}
	}
	cout << "\nThe Final Result after Transposing Matrix \n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < j; columns++) {
			cout << transMat[rows][columns] << "  ";
		}
		cout<<"\n";
	}
 	return 0;
}
Please Enter the rows and Columns of Matrix to Transpose =  3 3

Please Enter the Original Matrix Items
10 20 30
40 50 60
70 80 90

The Final Result after Transposing Matrix 
10  40  70  
20  50  80  
30  60  90 

C++ Program to Transpose a Matrix Example 2

In this C++ matrix transpose example, we used extra cout statements to show you the row, column values, original matrix item value, and the transposed matrix item value at each iteration.

#include<iostream>
using namespace std;

int main()
{
	int i, j, rows, columns;
	
	cout << "\nPlease Enter the rows and Columns of Matrix to Transpose =  ";
	cin >> i >> j;
	
	int orgMat[i][j], transMat[i][j];
	
	cout << "\nPlease Enter the Original Matrix Items\n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < i; columns++) {
			cin >> orgMat[rows][columns];
		}	
	}	
	for(rows = 0; rows < i; rows++)	{
		cout << "\n---The Result of " << rows + 1 << " Row Iteration---";
		for(columns = 0; columns < j; columns++) {
			transMat[columns][rows] = orgMat[rows][columns];
			
			cout << "\n---The Result of " << rows + 1 << " Row and "<< columns + 1 << " Column Iteration---";
			cout << "\nValue of transMat[columns][rows] = "<< transMat[columns][rows] << " and orgMat[rows][columns] =  " << orgMat[rows][columns];
		}
	}
	cout << "\nThe Final Result after Transposing Matrix \n";
	for(rows = 0; rows < i; rows++)	{
		for(columns = 0; columns < j; columns++) {
			cout << transMat[rows][columns] << "  ";
		}
		cout<<"\n";
	}
 	return 0;
}
C++ Program to Transpose a Matrix 2