C Example for Beginners: C Program to Find Transpose of a Matrix

(C programming Example for Beginners)

C Program to Find Transpose of a Matrix

In this example, you will learn to find the transpose of a matrix in C programming.


The transpose of a matrix is a new matrix that is obtained by exchanging the rows and columns.

In this program, the user is asked to enter the number of rows r and columns c. Their values should be less than 10 in this program.

Then, the user is asked to enter the elements of the matrix (of order r*c).

The program below then computes the transpose of the matrix and prints it on the screen.


Program to Find the Transpose of a Matrix


#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);

    // Assigning elements to the matrix
    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 the 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;
}

Output

Enter rows and columns: 2
3

Enter matrix elements:
Enter element a11: 1
Enter element a12: 4
Enter element a13: 0
Enter element a21: -5
Enter element a22: 2
Enter element a23: 7

Entered matrix:
1  4  0
-5  2  7

Transpose of the matrix:
1  -5
4  2
0  7 

 

C Example for Beginners: C Program to Find Transpose of a Matrix

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.