adplus-dvertising

C program to find transpose of a matrix

frame-decoration

C program to find transpose of a matrix

Problem Description

This C program finds the transpose of a given matrix. The transpose of a matrix is the matrix formed by interchanging the rows and columns of a matrix. In C, we use two-dimensional arrays to represent the matrix.

C program to find transpose of a matrix - Source code
     
                
  /*
 * C program to find the transpose of a given matrix
 */

#include <stdio.h>

int main()
{
    int mtrx[10][10], tmtrx[10][10];
    int rows, coulmns, i, j;

    printf("Enter rows and columns of matrix: ");
    scanf("%d %d", &rows, &coulmns);

    // Accepting matrix from user
    printf("\nEnter elements of matrix:\n");
    for(i=0; i<rows; i++)
        for(j=0; j<coulmns; j++)
        {
            printf("Enter element a%d%d: ",i+1, j+1);
            scanf("%d", &mtrx[i][j]);
        }

    // Displaying the matrix
    printf("\nEntered Matrix: \n");
    for(i=0; i<rows; i++)
    {

        for(j=0; j<coulmns; j++)
        {
            printf("%d  ", mtrx[i][j]);

        }
        printf("\n\n");
    }
    // Finding the transpose of matrix
    for(i=0; i<rows; i++)
        for(j=0; j<coulmns; j++)
        {
            tmtrx[j][i] = mtrx[i][j];
        }

    // Displaying the transpose of matrix
    printf("\nTranspose of Matrix:\n");
    for(i=0; i<coulmns; i++)
    {

        for(j=0; j<rows; j++)
        {
            printf("%d  ",tmtrx[i][j]);

        }
        printf("\n\n");
    }

    return 0;
}
     
      

Program Output

Case 1:

Enter elements of matrix:
Enter element a11: 1
Enter element a12: 2
Enter element a13: 3
Enter element a14: 45
Enter element a21: 56
Enter element a22: 67
Enter element a23: 68
Enter element a24: 34

Entered Matrix:
1  2  3  45

56  67  68  34


Transpose of Matrix:
1  56

2  67

3  68

45  34


Case 2:

Enter rows and columns of matrix: 3
3

Enter elements of matrix:
Enter element a11: 1
Enter element a12: 2
Enter element a13: 3
Enter element a21: 4
Enter element a22: 5
Enter element a23: 6
Enter element a31: 7
Enter element a32: 8
Enter element a33: 9

Entered Matrix:
1  2  3

4  5  6

7  8  9


Transpose of Matrix:
1  4  7

2  5  8

3  6  9

Program Explanation

1. First the user is asked to input the rows and columns of the matrix. The maximum number of rows and columns the matrix can have is 10.
2. User is asked to input the elements of the matrix. First for loop is for iterate through the row while the second inner loop is for the column.
3. To find the transpose of the matrix, the existent matrix is stored in new matrix by interchanging the subscripts of the elements. When we interchange the subscripts of elements(i;e a12 becomes a21, a23 becomes a32 and so on), rows becomes columns and vice versa.
4. At last, the transposed matrix is displayed using the for loops.