problem with taking transpos of Matrix

When i ran code below,it read matrix and display matrix twice without taking transpose of matrix.What is problem there kindly help me out


#include <iostream>

using namespace std;
const int arraySize=3;
void readMatrix(int a[][arraySize]);
void displayMatrix(int a[][arraySize]);
void transposMatrix(int a[][arraySize]);

int main()
{
int a[arraySize][arraySize];
readMatrix(a);
cout<<"Displaying the Orignal Matrix"<<endl;
displayMatrix(a);
transposMatrix(a);
cout<<endl<<endl;
cout<<"The transpose Matrix is "<<endl;
displayMatrix(a);
}
void readMatrix(int a[][arraySize])
{
int row,col;
for(int row=0;row<arraySize;row++)
{
for(int col=0;col<arraySize;col++)
{
cout<<"Plz enter a value for row "<<row<<","<<" and col "<<col<< " element ";
cin>>a[row][col];

}
cout<<endl;
}

}
void displayMatrix(int a[][arraySize])
{
int row,col;
for(row=0;row<arraySize;row++)
{
for(col=0;col<arraySize;col++)
{
cout<<a[row][col]<<"\t";
}
cout<<endl;
}
}

void transposMatrix(int a[][arraySize])
{

int temp;
int col;

for(int row=0; row<arraySize;row++)
{
for(int col=0;col<arraySize;col++)
{
temp=a[row][col];
a[row][col]=a[col][row];
a[col][row]=temp;

}

}
}
First: Use indents in your code to make it readable.
Second: Use the wrapper to make your code colored and easy to view.

Third: You have to copy your whole matrix before applying the transpose. You can't do this step by step like you're doing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void transposMatrix(int a[][arraySize])
{

    int temp;
    int col;
    int b[arraySize][arraySize]; //temporary matrix
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            b[i][j] = a[i][j]; //copy all elements of your matrix
        }
    }
    for(int row=0; row<arraySize;row++)
    {
        for(int col=0;col<arraySize;col++)
        {

            a[row][col]=b[col][row]; //transpose
        }

    }
}
Topic archived. No new replies allowed.