Transpose of a matrix

The transpose of a matrix is obtained by interchanging the rows with the corresponding columns. Let matrix a be.

12 13 14
15 16 17
18 19 11

The diagonal elements are the same both in matrix a and in the matrix obtained by transposing a. In this example, in the 0th row, interchange 13 with 15 and 14 with 18. After interchanging, the matrix becomes

12 15 18
13 16 17
14 19 11

In the first row, interchange the element that has not yet been interchanged in the 0th row; 17 with 19. After interchanging the elements, the matrix becomes:

12 15 18
3 16 19
11 17 11

In the next iteration, search for the nondiagonal un-swapped element. In this example, no such element is there, so the result of transposing matrix a is

12 15 18
13 16 19
14 19 11

Example

#include<stdio.h>
#include<conio.h>
#define ROW 3
#define COL 3

int main()
{
   void read(int a[][COL],int,int);
   void dis(int a[][COL],int,int);
   void trans(int a[][COL],int,int);
   int a[3][3];
   read(a,ROW,COL);
   printf("\nThe matrix is \n");
   dis(a,ROW,COL);
   trans(a,ROW,COL);
   printf("The tranpose of the matrix is\n");
   dis(a,ROW,COL);
   getchar();
   return 0;
}
void read(int c[3][3] ,int i ,int k)
{
    int j,l;
   printf("Enter the array \n");
   for(j=0;j<i;j++)
      for(l=0;l<k;l++)
             scanf("%d",&c[j][l]);
   fflush(stdin);
}
void dis(int d[3][3 ],int i,int k)
{
   int j,l;
   for(j=0;j<i;j++)
   {
      for(l=0;l<k;l++)
             printf("%d ",d[j][l]);
      printf("\n");
   }
}
void trans(int mat[][3],int k ,int l)
{
   int i,j,temp;
   for(i=0;i<k;i++)
       for(j=i+1;j<l;j++)
      {
         temp=mat[i][j];
         mat[i][j]=mat[j][i];
         mat[j][i]=temp;
      }
}

Explanation

Basic steps:

  1. Repeat step (2) for i=0,1,2, ………… (k–1 ) where k is the number of rows in the matrix.
  2. Repeat step (3–5) for j=(i+1),(i+2)…..{l–1) where l is the number of columns in the matrix.
  3. temp = mat[i][j]
  4. mat[i][j] = mat[j][i]
  5. mat[j][i] = temp