C program find transpose of square matrix without using another matrix

C program to find transpose of square matrix without using another matrix

This C program is to find transpose of a square matrix without using another matrix.For example, for a 2 x 2 matrix, the transpose of 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, only difference is that we use the same matrix instead of another matrix, and this is possible by using a temp variable.

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<i;j++) i.e. for(j=0;0<0;j++) Inner loop

Break as 0 is not less than 0

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

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

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

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

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

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

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] using the same matrix.

Program

#include<stdio.h>

void main()
{
    int mat[12][12];
    int i,j,row,col,temp;
    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 using same matrix
    for(i=0;i<row;i++)
    {
        for(j=0;j<i;j++)
        {
            temp=mat[i][j];
            mat[i][j]=mat[j][i];
            mat[j][i]=temp;
        }
    }

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

Output

Share Me!