Transpose a Matrix
A transpose maps the value at row i, column j to row j, column i.
What is Transpose a Matrix?
A transpose maps the value at row i, column j to row j, column i.
Exchange matrix rows and columns.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
// Visit columns first to print the transposed shape.
for (int column = 0; column < 3; ++column) { for (int row = 0; row < 2; ++row) printf("%s%d", row ? " " : "", matrix[row][column]); puts(""); }
}
1 4
2 5
3 6
C++
main.cpp
#include <array>
#include <iostream>
int main() {
std::array<std::array<int, 3>, 2> matrix{{{{1, 2, 3}}, {{4, 5, 6}}}};
// Visit columns first to print the transposed shape.
for (size_t column = 0; column < 3; ++column) { for (size_t row = 0; row < 2; ++row) std::cout << (row ? " " : "") << matrix[row][column]; std::cout << '\n'; }
}
1 4
2 5
3 6
C and C++ comparison
Nested loops visit every matrix coordinate and print columns from the original matrix as rows.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.