C program to find transpose of a matrix

Write a C program to read elements in a matrix and find transpose of the given matrix. How to find transpose of a given matrix in C.

Example: If elements of the matrix are:
1 2 3
4 5 6
7 8 9

Then its transpose is :
1 4 7
2 5 8
3 6 9

Required knowledge:

Basic C programming, For loop, Array, Matrix

Transpose of a matrix:

Transpose of a matrix A is defined as converting all rows into columns and columns into rows. Transpose of a matrix A is written as AT.
Transpose of a matrix

Algorithm to find transpose of a matrix:

To find transpose of a matrix A.
Step 1: Read elements in matrix A
Step 2: For each element in matrix A.
Bij = Aji (Where 1 ≤ i ≤ m and 1 ≤ j ≤ n).

Program:

/**
 * C program to find transpose of a matrix
 */

#include <stdio.h>

int main()
{
    int A[3][3], B[3][3];
    int row, col;

    /*
     * Reads elements in matrix A from user
     */
    printf("Enter elements in matrix of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /*
     * Finds the transpose of matrix A
     */
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            /* Stores each row of matrix A to each column of matrix B */
            B[row][col] = A[col][row];
        }
    }
    
    /*
     * Prints the original matrix A
     */ 
    printf("\nOriginal matrix: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            printf("%d ", A[row][col]);
        }

        printf("\n");
    }
    
    /*
     * Prints the transpose of matrix A
     */
    printf("Transpose of matrix A: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            printf("%d ", B[row][col]);
        }

        printf("\n");
    }

    return 0;
} 
Output
Enter elements in matrix of size 3x3:
1 2 3
4 5 6
7 8 9

Original matrix:
1 2 3
4 5 6
7 8 9
Transpose of matrix A:
1 4 7
2 5 8
3 6 9

Happy coding ;)


You may also like

Labels: , , ,