Find Transpose of a Matrix in C

Exercise:

Write a C Program to find transpose of a matrix.

Click Here to View the Solution!
#include <stdio.h>
int main() {
    int a[10][10], transpose[10][10], r, c, i, j;
    printf("Enter rows and columns: ");
    scanf("%d %d", &r, &c);
    printf("\nEnter matrix elements:\n");
    for (i = 0; i < r; ++i) {
        for (j = 0; j < c; ++j) {
            printf("Enter element a%d%d: ", i + 1, j + 1);
            scanf("%d", &a[i][j]);
        }
    }

    // Displaying matrix a[][]
    printf("\nEntered matrix: \n"); 
    for (i = 0; i < r; ++i) {
        for (j = 0; j < c; ++j) {
            printf("%d  ", a[i][j]);
            if (j == c - 1) {
                printf("\n");
            }
        }
    }

    // Finding the transpose of matrix a
    for (i = 0; i < r; ++i) {
        for (j = 0; j < c; ++j) {
            transpose[j][i] = a[i][j];
        }
    }

    // Displaying the transpose of matrix a
    printf("\nTranspose of the matrix:\n");
    for (i = 0; i < c; ++i) {
        for (j = 0; j < r; ++j) {
            printf("%d  ", transpose[i][j]);
            if (j == r - 1) {
                printf("\n");
            }
        }
    }
    return 0;
}
Click Here to View the Output!
Enter rows and columns: 2 2 

Enter matrix elements:  
Enter element a11: 6  
Enter element a12: 4  
Enter element a21: 2  
Enter element a22: 8  
                                        
Entered matrix: 
6  4   
2  8 

Transpose of the matrix: 
6  2   
4  8  
Click Here to View the Explanation!
  • This program is used to determine the transpose of a matrix.
  • In main(), two matrices are declared; each with a limit of 10 values.
  • The program requests the user to enter the rows and columns of the matrix and stores them in the variables r and c using the scanf() function.
  • The program then requests the user to enter the elements that are assigned to the matrix a[i][j].
  • a[i][j] is then finally printed row-wise. And once the inner loop reaches to the (c – 1)th value, the loop exits and the outer loop starts executing again for the second row.
  • The transpose of the matrix is found by assigning a[i][j] to transpose[j][i].
  • The transpose matrix transpose[j][i] is finally displayed column-wise and once the inner loop reaches to the (r – 1)th value, the loop exits and the outer loop starts executing again for the second column.