C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Transpose of a matrix

C Program: Transpose of a matrix

C

#include <stdio.h>

 

int main() {

    int a[10][10], transpose[10][10];

    int i, j, rows, cols;

 

    // Input number of rows and columns

    printf("Enter number of rows: ");

    scanf("%d", &rows);

    printf("Enter number of columns: ");

    scanf("%d", &cols);

 

    // Input elements of matrix

    printf("\nEnter elements of the matrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    // Compute transpose

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            transpose[j][i] = a[i][j];

        }

    }

 

    // Display original matrix

    printf("\nOriginal Matrix:\n");

    for (i = 0; i < rows; i++) {

        for (j = 0; j < cols; j++) {

            printf("%d\t", a[i][j]);

        }

        printf("\n");

    }

 

    // Display transpose matrix

    printf("\nTranspose of Matrix:\n");

    for (i = 0; i < cols; i++) {

        for (j = 0; j < rows; j++) {

            printf("%d\t", transpose[i][j]);

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
INPUT :
Enter number of rows: 2
Enter number of columns: 3
Enter elements of the matrix:
1 2 3
4 5 6

OUTPUT :
Original Matrix:
1   2   3
4   5   6

Transpose of Matrix:
1   4
2   5
3   6


Explanation

  1. Transpose of a matrix is obtained by swapping rows and columns.

                 transpose[j][i] = a[i][j] 

  1. Two nested loops are used to interchange elements.
  2. The original and transposed matrices are displayed separately.