C++ での行列の転置

行列の転置は、その行と列を交換することによって得られます。

アルゴリズム:

1. 行数と列数を入力します。

2. 行と列を入れ替えます。

以下のコードは関数を使用していません。関数を使って書くこともできます。

コード:

#include<iostream>
using namespace std;
int row,col;
int main()
{
    int val,row,col;
    //insert rows and columns for matrix
    cin>>row;
    cin>>col;
    int a[row][col];
	//insert values in the matrix 
	cout<<"\n a: \n";
	for(int i=0;i<row;i++)
	{
		for(int j=0;j<col;j++)
		{
			cin>>val;
			a[i][j]=val;
		}
	}
   
   //puting content of rows of a in columns of b
    int b[col][row];
    for(int j=0;j<row;j++)
	{
		for(int i=0;i<col;i++)
		   	b[i][j]=a[j][i];
	}
   
   //copy contents of b in a
    for(int i=0;i<col;i++)
	{
		for(int j=0;j<row;j++)
			a[i][j]=b[i][j];
	}
	
	//display a
	for(int i=0;i<col;i++)
	{
		for(int j=0;j<row;j++)
			cout<<a[i][j]<<" ";
		cout<<"\n";
	}
	
	return 0;
}

出力:

3 3 

1 2 3 
4 5 6 
7 8 9 

a: 1 4 7
   2 5 8 
   3 6 9