Pages

Sunday, 12 July 2015

Transpose of a matrix

C program to transpose a matrix
Coding:
#include<stdio.h>
#include<stdlib.h>
int main()
{
      int **a,row,col,i,j,**b;
      printf("Please enter the total number of rows & columns:");
      scanf("%d%d",&row,&col);
      a=(int**)malloc(row*sizeof(int));
      b=(int**)malloc(row*sizeof(int));
      for(i=0;i<row;i++)
      {
        a[i]=(int*)malloc(col*sizeof(int));
        b[i]=(int*)malloc(col*sizeof(int));
      }
      printf("Please enter the elements:\n");
      for(i=0;i<row;i++)
        for(j=0;j<col;j++)
            scanf("%d",&a[i][j]);
      printf("Matrix elements before transpose:");
      for(i=0;i<row;i++)
      {
        printf("\n");
        for(j=0;j<col;j++)
        {
            printf("%d ",a[i][j]);
        }
      }
      for(i=0;i<col;i++)
        for(j=0;j<row;j++)
            b[i][j]=a[j][i];
      printf("\nMatrix elements after transpose:");
      for(i=0;i<col;i++)
      {
        printf("\n");
        for(j=0;j<row;j++)
        {
            printf("%d ",b[i][j]);
        }
      }
      return 0;
}


Output:
Please enter the total number of rows & columns:3 2
Please enter the elements:
1 2
3 4
5 6
Matrix elements before transpose:
1 2
3 4
5 6
Matrix elements after transpose:
1 3 5
2 4 6