Matrix Transpose
Given a matrix of R rows and C columns, print its transpose where rows become columns and vice versa.
Understand the Problem
Problem Statement
Given a matrix of R rows and C columns as the input, the program must print the transpose of the input matrix.
The transpose of a matrix is obtained by swapping rows with columns. The element at position (i, j) in the original matrix becomes the element at position (j, i) in the transposed matrix.
Constraints
- 1 <= R, C <= 1000
- Matrix elements can be any valid integers
- Memory constraints must be considered for large matrices
- Time complexity should be O(R × C)
Examples
4 3
62 9 88
72 81 31
3 99 72
3 64 5162 72 3 3
9 81 99 64
88 31 72 51The original 4×3 matrix is transposed into a 3×4 matrix. The first column of the original (62, 72, 3, 3) becomes the first row of the transpose. Similarly, the second column (9, 81, 99, 64) becomes the second row, and the third column (88, 31, 72, 51) becomes the third row.
3 3
1 2 3
4 5 6
7 8 91 4 7
2 5 8
3 6 9The original 3×3 matrix is transposed into another 3×3 matrix. The first column (1, 4, 7) becomes the first row, the second column (2, 5, 8) becomes the second row, and the third column (3, 6, 9) becomes the third row.
Solution
#include <stdio.h>
int main() {
int r, c;
scanf("%d %d", &r, &c);
int matrix[r][c];
// Read the matrix
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Print transpose
for (int j = 0; j < c; j++) {
for (int i = 0; i < r; i++) {
printf("%d", matrix[i][j]);
if (i < r - 1) {
printf(" ");
}
}
printf("\n");
}
return 0;
}Step-by-step explanation:
- Read R and C from standard input using scanf
- Declare a 2D array with dimensions R×C using variable-length array syntax
- Use nested loops to read all matrix elements: outer loop for rows, inner loop for columns
- For transpose: swap the loop order - outer loop iterates through columns (0 to C-1), inner loop iterates through rows (0 to R-1)
- Print each element matrix[i][j] followed by a space (except for the last element in each row)
- After printing all elements of a column (which becomes a row in transpose), print a newline