C program to find transpose of a matrix

C program to find transpose of a matrix

This C program is to find transpose of a matrix.For example, for a 2 x 2 matrix, the transpose of a matrix{1,2,3,4} will be equal to transpose{1,3,2,4}.

1     2                                     1         3

—-> transpose

3    4                                      2        4

Logic

We interchange rows and columns to get the transpose of the matrix.

Dry Run of the Program

Take input mat[][] and store elements in mat{1,2}{3,4}

Take input ‘row’ and no of rows(row) as 2

Take input ‘col’ and no of columns(col) as 2

1st iteration for(i=0;i<row;i++) i.e. for(i=0;0<2;i++) Outer loop

1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop

transpose[j][i]=mat[i][j];  i.e. transpose[0][0]=mat[0][0]  i.e. transpose[0][0]=1

2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop

transpose[j][i]=mat[i][j];  i.e. transpose[1][0]=mat[0][1]  i.e. transpose[1][0]=2

2nd iteration for(i=1;i<row;i++) i.e. for(i=1;1<2;i++) Outer loop

1st iteration for(j=0;j<col;j++) i.e. for(j=0;0<2;j++) Inner loop

transpose[j][i]=mat[i][j];  i.e. transpose[0][1]=mat[1][0]  i.e. transpose[0][1]=3

2nd iteration for(j=1;j<col;j++) i.e. for(j=1;1<2;j++) Inner loop

transpose[j][i]=mat[i][j];  i.e. transpose[1][1]=mat[1][1]  i.e. transpose[1][1]=4

Now we break out of inner loop and then outer loop.

Hence the transpose of the matrix[1,2][3,4] is tranpose[1,3][2,4].

Program

#include<stdio.h>

void main()
{
    int mat[12][12],transpose[12][12];
    int i,j,row,col;
    printf("Enter the number of rows and columns for 1st matrix\n");
    scanf("%d%d",&row,&col);
    printf("Enter the elements of the matrix\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            scanf("%d",&mat[i][j]);
        }
    }


    printf("The matrix\n");
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            printf("%d\t",mat[i][j]);
        }
        printf("\n");
    }
    //transpose logic
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
            transpose[j][i]=mat[i][j];
        }
    }

    printf("The transpose of the matrix is\n");
    for(i=0;i<col;i++)
    {
        for(j=0;j<row;j++)
        {
            printf("%d\t",transpose[i][j]);
        }
        printf("\n");
    }
}

Output

Share Me!