Check The Programming Section
Transpose of a matrix can be done two ways:
using a different matrix
within a same matrix
In this implementation we have used the same matrix for transpose to save extra required space. This approach is useful for the square matrix only. For example,
If 3 is given as input to number of rows and columns and the given matrix is
1 2 3
4 5 6
7 8 9
Then the transpose of the matrix will be
1 4 7
2 5 8
3 6 9
Number of rows and cols given 3 as input at line 15
Two for loops from line 16-20 are used to take input the values as
1 2 3 4 5 6 7 8 9
The print function get called at line 23 to print the matrix as follows:
1 2 3
4 5 6
7 8 9
The required code to transpose the matrix is written from line 24-30
for i = 0, j = 0 and 0 < 0 is false no chnage in the matrix
for i = 1, j = 0 and 0 <1 is true and values of first row get swapped with values of first column.
temp = mat[0][1] = 2
mat[0][1] = mat[1][0] = 4
mat[1][0] = temp = 2
for i = 1, j = 1 and 1<1 false, no change
Output after second iteration
1 4 3
2 5 6
7 8 9
for i = 2, j = 0 and 0<2 is true and matrix after this iteration
1 4 7
2 5 6
3 8 9
for i = 2, j=1 1<2 is true and matrix after this iteration of inner loop is
1 2 3
4 5 8
7 6 9
Both the loop is terminated as j=2, 2<2 false