I have to write a program to allow a user to input the number of rows and the number of columns of a matrix. The program will then construct the transpose of the matrix and display the transpose to the user, it is also supposed to display the trace and determinant of the matrix. I am having a problem with the output for the transpose, whenever the matrix is not a perfect square I get random numbers. This is my code:
int main()
{
int matrix[10][10];
int row, column, i, j;
int temp = 0;
//size of matrix
cout << "Enter number of rows: ";
cin >> row;
cout << "Enter number of columns: ";
cin >> column;
// read the matrix values ( original matrix )
cout << "Enter the elements: \n";
for (i = 0; i < row; i++)
for (j = 0; j < column; j++)
cin >> matrix[i][j];
cout << "Matrix: \n";
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
cout << matrix[i][j] << ' ';
cout << endl;
}
// transpose the matrix values ( the matrix transposed )
cout << "Transpose of a Matrix: \n";
for (j = 0; j < row; j++)
{
for (i = 0; i < column; i++)
cout << matrix[i][j] << ' ';
cout << endl;
}
// trace of a matrix
int trace = 0;
if (row == column)
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
trace += matrix[i][i];
cout << "Trace of a Matrix: \n";
cout << trace << endl;
}
else
{
cout << "The trace will not be computed \n"
<< "The given matrix is not a perfect square" << endl;
}
// determinant of Matrix
int det = 0;
if (row == 2 && column == 2)
{
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
for (i = 0; i < row; i++)
cout << "Determinant of the Matrix: \n";
det = ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
cout << det << endl;
}
}
else
{
cout << "The determinant will not be computed \n"
<< "The given matrix is not a square" << endl;
}
return 0;
}
If I were to enter 3 rows and 2 columns and random elements my output looks like this:
Enter number of rows: 3
Enter number of columns : 2
Enter the elements:
1 5 6 -4 2 3
Matrix:
1 5
6 -4
2 3
Transpose of a Matrix:
1 6
5 -4
-858993460 -858993460
The trace will not be computed
The given matrix is not a perfect square
The determinant will not be computed
The given matrix is not a square
Is there something wrong in my code that causes -858993460 and -858993460 to come up?
Read more here: https://stackoverflow.com/questions/67015944/c-matrix-problem-incorrect-output-for-transpose-matrix
Content Attribution
This content was originally published by An_Be at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.