How to transpose a square matrix in C
Overview
Read one matrix (called Matrix 1) using the standard input (scanf), and try to transpose the matrix to get the result.
Transpose matrix means the original matrix rows will be changed to columns and columns to rows.
The result is stored in the new matrix, which is the transpose matrix.
Example
Let’s first take a 2x2 matrix and try to transpose it.
Matrix 1:
The resultant matrix will look like this :
Transpose matrix:
Algorithm
Generally, the transpose of the matrix is denoted by T.
When reading the data, we need to use loops.
We also need loops to access the transpose of the matrix.
After transposing the elements, we store the data in the resultant matrix.
The pseudo code looks like this:
for(i=0;i<N; i++)
{
for(j=0;j<N ;j++)
{
Transpose[j][i] = Matrix[i][j];
}
}
Code
To run the code below, first give the input value of n (size), followed by values of the matrix.
After giving all the inputs, we’ll get the resultant matrix which is the transpose of Matrix 1.
Note: For a 2x2 matrix, we can give the values of a matrix as follows: 2 1 2 3 4
Here, 2 is the value of
nand we have 4 values for the matrix. Here, “2 1 2 3 4” would be the input.
#include<stdio.h>int main(){int i, j, N; // Declaration of variables.scanf("%d", &N); // Reading the value of n which represnts size of the matrix.int Matrix[N][N], Transpose[N][N]; // Declaring the matrices.//Reading the Matrixfor(i=0;i<N;i++){for(j=0;j<N;j++){scanf("%d",&Matrix[i][j]);}}// Transposing the matrixfor(i=0;i<N;i++){for(j=0;j<N;j++){Transpose[j][i] =Matrix[i][j]; // In this step we interchange the rows ans columns.}}// Printing the matrixfor(i=0;i<N;i++){for(j=0;j<N;j++){printf("%d ",Transpose[i][j]);}printf("\n");}return 0;}
Enter the input below
Explanation
-
Line 4: The
Nrepresents the dimensions of the matrix. -
Line 6: We declare two matrices. The matrix
Matrix[n][n]represents the original matrix and the matrixTranspose[n][n]represents the transpose of the original matrix.- First, we take the value of
N, which represents the size of the matrix.
- First, we take the value of
-
Line 8: We read the first matrix using the
forloop. -
Line 16: After reading the matrix, we transpose the matrix. In this step, we interchange the rows with columns or columns with rows.
-
Line 24: This transposition of the matrix is put into the resultant matrix, and finally, we use the
forloop to print the final resultant matrix.