We need to read the elements of a matrix using the standard input (scanf
) and transpose the matrix to get the result. In the solution code we’ll read the input of rows and columns of the matrix from the standard input. The result should be stored in the new matrix transpose
.
Let’s first take a 2x3 matrix and transpose it.
Original Matrix:
Transpose Matrix: The resultant matrix will look like this:
In the transpose matrix, the rows will be exchanged with columns and vice versa.
Generally, the transpose of the matrix is denoted by T
. The transpose of the matrix means that we need to change its rows into columns or columns into rows.
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.
for(i=0 ; i<rows ; i++) {
for(j=0 ; j<cols ; j++) {
trans[j][i] =a[i][j];
}
}
rows
represent the size of the rows.cols
represent the size of the columns.a[rows][cols]
represents the original matrix.trans[cols][rows]
represents the transpose of the matrix or the resultant matrix.To run the code below, give the input value for rows
and cols
followed by element values of the matrix.
After giving all the inputs, we get the resultant matrix which is the transpose of the input matrix.
#include <stdio.h>#include <string.h>#include <math.h>#include <stdlib.h>int main(){int rows,cols; // Declaring the variablesscanf("%d %d",&rows,&cols);if(rows <= 0 || cols <=0) {printf("Values for rows and coulmns must be positive and greater than zero.\n");exit(0);}int a[rows][cols] ; // Declaring the matrixint trans[cols][rows] ;// Declaring the transpose matrix// Reading of the original matrixint value_count = 0 ;for(int i=0;i<rows;i++){for(int j=0;j<cols;j++){scanf("%d",&a[i][j]);value_count++;}}// Transposing the matrixfor(int i=0;i<rows;i++){for(int j=0;j<cols;j++){trans[j][i]=a[i][j];}}// Printing the transpose matrixint i,j;for(i=0;i<cols;i++){for( j=0;j<rows;j++){printf("%d ",trans[i][j]);}printf("\n");}return 0;}
Enter the input below
In the above code first we will be reading the size for the rows and columns.
After reading the size then we will be reading a matrix from the user end.
Then we will interchange the rows with columns or columns with rows. As soon as we interchange the rows and columns we print the matrix.