C Online Compiler
Example: Simple Dense Matrix Transpose in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Simple Dense Matrix Transpose #include <stdio.h> #define MAX_ROWS 4 #define MAX_COLS 5 void printMatrix(int rows, int cols, int matrix[MAX_ROWS][MAX_COLS]) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } } void printTransposedMatrix(int rows, int cols, int matrix[MAX_ROWS][MAX_COLS]) { for (int i = 0; i < cols; i++) { // Iterate through columns of original to get rows of transpose for (int j = 0; j < rows; j++) { // Iterate through rows of original to get columns of transpose printf("%d ", matrix[j][i]); } printf("\n"); } } int main() { // Step 1: Define a sample sparse matrix as a dense 2D array int matrix[MAX_ROWS][MAX_COLS] = { {0, 0, 3, 0, 0}, {0, 0, 0, 0, 7}, {0, 1, 0, 0, 0}, {0, 0, 0, 9, 0} }; int rows = MAX_ROWS; int cols = MAX_COLS; printf("Original Matrix (%dx%d):\n", rows, cols); printMatrix(rows, cols, matrix); printf("\nTransposed Matrix (%dx%d):\n", cols, rows); printTransposedMatrix(rows, cols, matrix); return 0; }
Output
Clear
ADVERTISEMENTS