C Online Compiler
Example: Matrix Transposition in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Matrix Transposition #include <stdio.h> #define MAX_ROWS 10 #define MAX_COLS 10 int main() { int original[MAX_ROWS][MAX_COLS]; int transpose[MAX_COLS][MAX_ROWS]; // Dimensions are swapped for the transpose int rows, cols, i, j; // Step 1: Get matrix dimensions from the user printf("Enter the number of rows and columns for the matrix (max %d x %d):\n", MAX_ROWS, MAX_COLS); if (scanf("%d %d", &rows, &cols) != 2 || rows <= 0 || cols <= 0 || rows > MAX_ROWS || cols > MAX_COLS) { printf("Invalid dimensions. Please enter positive values within limits.\n"); return 1; } // Step 2: Input elements of the original matrix printf("Enter elements of the matrix:\n"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("Enter element original[%d][%d]: ", i, j); if (scanf("%d", &original[i][j]) != 1) { printf("Invalid input. Please enter an integer.\n"); return 1; } } } // Step 3: Print the original matrix printf("\nOriginal Matrix:\n"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("%d\t", original[i][j]); } printf("\n"); } // Step 4: Compute the transpose matrix // Rows of original become columns of transpose, and vice-versa for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { transpose[j][i] = original[i][j]; } } // Step 5: Print the transposed matrix printf("\nTransposed Matrix:\n"); for (i = 0; i < cols; i++) { // Iterate up to original 'cols' for rows of transpose for (j = 0; j < rows; j++) { // Iterate up to original 'rows' for columns of transpose printf("%d\t", transpose[i][j]); } printf("\n"); } return 0; }
Output
Clear
ADVERTISEMENTS