C Online Compiler
Example: Matrix Transpose in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Transpose #include <stdio.h> int main() { // Define the original matrix (example 3x2) int original_matrix[3][2] = {{1, 2}, {3, 4}, {5, 6}}; int rows = 3; int cols = 2; // Declare the transpose matrix with swapped dimensions (cols x rows) int transpose_matrix[cols][rows]; printf("Original Matrix:\n"); // Step 1: Print the original matrix to demonstrate its initial state for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", original_matrix[i][j]); } printf("\n"); } // Step 2: Compute the transpose // Iterate through the original matrix rows for (int i = 0; i < rows; i++) { // Iterate through the original matrix columns for (int j = 0; j < cols; j++) { // Assign element from original[i][j] to transpose[j][i] transpose_matrix[j][i] = original_matrix[i][j]; } } printf("\nTransposed Matrix:\n"); // Step 3: Print the transposed matrix // Note: When printing, iterate with the new dimensions (cols for rows, rows for cols) for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { printf("%d ", transpose_matrix[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS