Transpose a Matrix
Exchange matrix rows and columns.
What is Transpose a Matrix?
A transpose maps the value at row i, column j to row j, column i.
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.
See how it works
Press transpose to swap rows and columns. Point at a cell to see its new position and memory offset.
C and C++ code examples
#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
#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 exposes small procedural APIs and makes representation details explicit.
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.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Row Sums Add up every row of a grid. Easy
- Matrix Multiplication Multiply two matrices, the operation behind every layer of a neural network. Easy