Find transpose of matrix – C Program

C program to read matrix of size 3*3 and display transpose of matrix.

Solution:

Transpose is conversion of rows into column and column into rows.

#include <stdio.h>
int main()
{
     int a[4][4],t[4][4],i,j;
     printf("Enter Elements for Matrix of Size 3*3:\n\n");
     for(i=0;i<=2;i++)
          for(j=0;j<=2;j++)
          {
               scanf("%d",&a[i][j]);
          }
     printf("\n3*3 Matrix:\n\n");
     for(i=0;i<=2;i++)
     {
          for(j=0;j<=2;j++)
          {
               printf("%d ",a[i][j]);
          }
          printf("\n");
     }
     for(i=0;i<=2;i++)
          for(j=0;j<=2;j++)
          {
               t[j][i]=a[i][j]; // Transpose the matrix
          }
     /* Print the transpose matrix */
     printf("\nTranspose of Matrix:\n\n");
     for(i=0;i<=2;i++)
     {
          for(j=0;j<=2;j++)
          {
               printf("%d ",t[i][j]);
          }
     printf("\n");
     }
     return 0;
}


Output:

transpose matrix

Q. Write a C program to display transpose of matrix using user defined function.

Solution:

#include<stdio.h>
/*User defined function transpose */
void transpose(int b[3][3])
{
     int t[3][3], k, l;
     for(k = 0; k < 3; k++)
     {
          for(l = 0; l < 3; l++)
          {
               t[l][k] = b[k][l];
          }
     }
     printf("\nTranspose of Matrix :\n");
     for(k = 0; k < 3; k++)
     {
          for(l = 0; l < 3; l++)
          {
               printf("%d\t", t[k][l]);
          }
          printf("\n");
     }
}
int main()
{
     int i,j,a[3][3];
     printf("Enter Elements for Matrix of Size 3*3:\n\n");
     for(i = 0; i < 3; i++)
          for(j = 0; j < 3; j++)
               scanf("%d", &a[i][j]);
     printf("\n3*3 Matrix:\n");
     for(i = 0; i < 3; i++)
     {
          for(j = 0; j < 3; j++)
          {
               printf("%d\t", a[i][j]);
          }
          printf("\n");
     }
     transpose(a); //calls function transpose
     return 0;
}


Output:

transpose matrix