Transpose of a matrix in C

Created with Sketch.

Transpose of a Matrix in C

Introduction

The transpose of a matrix is a fundamental operation in linear algebra, where the rows of a matrix are swapped with its columns. This operation is essential in various mathematical and computational applications. In this blog post, we will explore the concept of matrix transposition, understand the algorithm to find the transpose of a matrix, and implement it in the C programming language. The post will include the logic behind matrix transposition, a step-by-step guide to the algorithm, and the C program’s output.

C Program for Transposing a Matrix

Now, let’s implement the algorithm in C:

#include <stdio.h>

#define MAX_ROWS 10
#define MAX_COLS 10

void transposeMatrix(int mat[MAX_ROWS][MAX_COLS], int rows, int cols) {
    int transposed[MAX_COLS][MAX_ROWS];

    // Transpose the matrix
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            transposed[j][i] = mat[i][j];
        }
    }

    // Print the original matrix
    printf("Original Matrix:\n");
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            printf("%d\t", mat[i][j]);
        }
        printf("\n");
    }

    // Print the transposed matrix
    printf("\nTransposed Matrix:\n");
    for (int i = 0; i < cols; ++i) {
        for (int j = 0; j < rows; ++j) {
            printf("%d\t", transposed[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int rows, cols;

    // Input matrix dimensions
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);

    int matrix[MAX_ROWS][MAX_COLS];

    // Input matrix elements
    printf("Enter the matrix elements:\n");
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            scanf("%d", &matrix[i][j]);
        }
    }

    // Transpose the matrix and print the result
    transposeMatrix(matrix, rows, cols);

    return 0;
}

Output:

For example, if the user enters a 2×3 matrix:

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

The output will be:

 
Original Matrix:
1       2       3
4       5       6

Transposed Matrix:
1       4
2       5
3       6

Conclusion

Matrix transposition is a common operation in linear algebra and computer science. Understanding how to find the transpose of a matrix and implementing it in a programming language like C is essential for various applications. This blog post has provided an explanation of the transpose operation, the algorithm to achieve it, and a practical C program. Feel free to experiment with different matrix dimensions and elements to observe how the program correctly transposes the input matrix. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *