Transpose of a Matrix: C, C++, Java and Python Code
Full code to find the transpose of a matrix in C, C++, Java and Python. Covers square and rectangular inputs, in-place swap, and O(rows*cols) complexity.
Transposing a matrix is one of the shortest programs you will write and one of the most reliably tested topics in Wipro NLTH and TCS NQT coding rounds.
What a Matrix Transpose Does
The transpose of a matrix turns its rows into columns. The element at position [i][j] in the original matrix moves to position [j][i] in the result. A matrix with 2 rows and 3 columns produces a transpose with 3 rows and 2 columns.
Walk through this 2x3 example:
Original (2 rows x 3 cols):
1 2 3
4 5 6
Transpose (3 rows x 2 cols):
1 4
2 5
3 6
Tracing the movement:
- Element at
[0][1](value 2) moves to[1][0]in the transpose. - Element at
[1][2](value 6) moves to[2][1]in the transpose. - The assignment rule in code:
trans[j][i] = mat[i][j].
Two implementation strategies cover all cases. Out-of-place transpose creates a new matrix with swapped dimensions. In-place transpose modifies the original by swapping elements across the main diagonal. Out-of-place works for any shape. In-place only works when the matrix is square (same number of rows and columns), because swapping mat[i][j] with mat[j][i] must stay within the original array bounds.
Transpose in C
The C implementation uses variable-length arrays (C99 and later) for dynamic sizing. Declare a second array with swapped dimensions, then fill it with the transposed values.
#include <stdio.h>
int main() {
int rows, cols;
printf("Enter rows and columns: ");
scanf("%d %d", &rows, &cols);
int mat[rows][cols];
int trans[cols][rows];
printf("Enter matrix elements:\n");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
scanf("%d", &mat[i][j]);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
trans[j][i] = mat[i][j];
printf("Transpose:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++)
printf("%d ", trans[i][j]);
printf("\n");
}
return 0;
}
Sample input and output:
Input:
2 3
1 2 3
4 5 6
Output:
1 4
2 5
3 6
The outer loop runs rows times and the inner loop runs cols times. The single assignment trans[j][i] = mat[i][j] does all the work. Everything else is input and output scaffolding.
Transpose in C++
The C++ version replaces fixed arrays with std::vector for cleaner memory handling. The transpose logic is identical to C.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int rows, cols;
cout << "Enter rows and columns: ";
cin >> rows >> cols;
vector<vector<int>> mat(rows, vector<int>(cols));
vector<vector<int>> trans(cols, vector<int>(rows));
cout << "Enter matrix elements:\n";
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
cin >> mat[i][j];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
trans[j][i] = mat[i][j];
cout << "Transpose:\n";
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++)
cout << trans[i][j] << " ";
cout << "\n";
}
return 0;
}
Sample input and output:
Input:
3 3
1 2 3
4 5 6
7 8 9
Output:
1 4 7
2 5 8
3 6 9
Using std::vector removes the C99 VLA dependency and avoids stack-overflow issues on large matrices. The declaration vector<vector<int>> trans(cols, vector<int>(rows)) mirrors the math directly: swap the size parameters to get the transposed shape. In competitive coding rounds with tight time limits, std::vector also lets you query .size() dynamically, so you never need to hardcode the matrix dimensions.
Transpose in Java
Java uses 2D arrays with explicit size declarations. The Scanner class handles input, and the transpose logic follows the same double-loop pattern.
import java.util.Scanner;
public class MatrixTranspose {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows and columns: ");
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] mat = new int[rows][cols];
int[][] trans = new int[cols][rows];
System.out.println("Enter matrix elements:");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = sc.nextInt();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
trans[j][i] = mat[i][j];
System.out.println("Transpose:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++)
System.out.print(trans[i][j] + " ");
System.out.println();
}
}
}
Sample input and output:
Input:
2 4
1 2 3 4
5 6 7 8
Output:
1 5
2 6
3 7
4 8
Java’s int[rows][cols] and int[cols][rows] declaration makes the dimension swap explicit. The JVM handles memory allocation, so no manual free-up is needed. Java is more verbose than Python for matrix I/O, but its type declarations make the data shape visible at a glance, which reduces debugging time during a timed test.
Transpose in Python
Python’s list comprehension expresses the transpose mapping in a single readable line.
rows = int(input("Enter rows: "))
cols = int(input("Enter cols: "))
mat = []
for i in range(rows):
row = list(map(int, input().split()))
mat.append(row)
# Out-of-place transpose using list comprehension
trans = [[mat[i][j] for i in range(rows)] for j in range(cols)]
print("Transpose:")
for row in trans:
print(*row)
Sample input and output:
Input:
2 3
1 2 3
4 5 6
Output:
1 4
2 5
3 6
The inner comprehension mat[i][j] for i in range(rows) builds one column of the transpose. The outer loop iterates over j in range(cols) to collect all columns.
NumPy 1-Liner
For data-science contexts, NumPy’s .T attribute returns the transposed matrix without writing any loops:
import numpy as np
mat = np.array([[1, 2, 3], [4, 5, 6]])
print(mat.T)
# Output:
# [[1 4]
# [2 5]
# [3 6]]
Placement coding rounds expect the manual loop approach. The NumPy version becomes relevant in data-science or ML role interviews where demonstrating library fluency is part of the test.
In-Place Transpose for Square Matrices
Out-of-place transpose always allocates a new matrix. When memory is tight and the matrix is square, an in-place swap reduces space usage to O(1).
The approach: iterate only over the upper triangle (positions where j > i) and swap mat[i][j] with mat[j][i].
/* In-place square matrix transpose (C example, n x n matrix) */
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
Starting the inner loop at j = i + 1 instead of j = 0 prevents double-swapping. If both loops started at 0, each pair of elements would be swapped twice, restoring the original values.
For a 3x3 input:
Before: After in-place transpose:
1 2 3 1 4 7
4 5 6 -> 2 5 8
7 8 9 3 6 9
This method does not work for rectangular matrices. If rows and cols differ, the index mat[j][i] falls outside the array’s declared bounds, causing undefined behaviour in C/C++ and an ArrayIndexOutOfBoundsException in Java.
Time and Space Complexity
| Approach | Time | Space | Rectangular matrix? |
|---|---|---|---|
| Out-of-place (all languages) | O(rows x cols) | O(rows x cols) | Yes |
| In-place (C, C++, Java) | O(rows x cols) | O(1) | No (square only) |
NumPy .T (Python) | O(rows x cols) | O(rows x cols) | Yes |
Both strategies visit every element exactly once, so time is the same across all approaches. The difference is space: out-of-place needs a full second matrix; in-place needs only a single temp variable.
Choosing a Language for Placement Coding Rounds
Most placement platforms support all four languages. Wipro NLTH uses HirePro and TCS NQT uses iMocha; both allow C, C++, Java, and Python. For a problem as direct as matrix transpose, the choice of language affects writing speed more than correctness.
| Language | Approx. lines (transpose) | I/O verbosity | Common in placement coding |
|---|---|---|---|
| C | ~25 | High (printf/scanf) | Moderate |
| C++ | ~22 | Medium (cin/cout) | High (most common choice) |
| Java | ~25 | Medium (Scanner) | Medium |
| Python | ~10 | Low | High (fastest to write) |
If the coding round allows Python 3, it is worth defaulting to Python for matrix problems. The list comprehension reads close to plain English, debug cycles are shorter than in C, and the interpreter surfaces index errors explicitly rather than returning silent garbage values. If performance matters because of large matrix sizes or strict time limits, C++ is the standard choice in competitive contexts.
Where Matrix Problems Appear in Placement Tests
Matrix problems are standard fare in Wipro NLTH and TCS NQT coding sections. Transpose is the entry-level variant. Related problems tested in the same sessions include: rotate a matrix by 90 degrees, find the spiral-order traversal, check if a matrix is symmetric, and compute the diagonal sum. All of them are built on the same indexing logic as transpose.
Wipro’s two main hiring tracks differ in what the coding round tests:
| Track | CTC Band | Coding Round Focus |
|---|---|---|
| Standard / Velocity | 3.5 to 4.0 LPA | Fundamentals: loops, arrays, matrices |
| Centres of Excellence (CoE) | Premium (not publicly disclosed) | Advanced DSA, AI/data problem-solving |
See Wipro NLTH syllabus and exam pattern for the current section breakdown, and Wipro placement papers for past coding questions from the NLTH. Once the coding test clears, the Wipro interview questions guide covers what interviewers ask in the technical round that follows.
TCS NQT typically offers two problems per coding attempt: one easier (array or loop), one medium (matrix or string manipulation). Matrix transpose and its variants appear in the easier slot. Clearing it quickly leaves time for the harder problem.
The AI Context for Matrix Operations
According to The Hindu Business Line, Wipro operates 50 university Centres of Excellence where it co-develops AI, cybersecurity, and data curriculum with partner universities. Candidates from CoE programs enter on a premium track with a differentiated interview process. For those candidates, matrix operations are not just a coding round question; they are the mathematical foundation for attention mechanisms, neural-network weight layers, and gradient computations in ML models.
The 2026 AI roadmap for Indian engineering students covers what the gap between standard placement prep and AI-track preparation actually looks like, end to end.
The transpose loop is 5 lines of C code. What separates a Wipro CoE candidate from a Velocity candidate is knowing what that loop does inside a transformer’s attention matrix. TinkerLLM is where you build that understanding hands-on: real LLM API calls for ₹299, documented in a GitHub notebook you can show at the interview.
Primary sources
Frequently asked questions
What is the transpose of a matrix?
The transpose of a matrix is formed by swapping its rows and columns. Element at position [i][j] in the original moves to [j][i] in the transposed matrix. A 2x3 matrix becomes a 3x2 matrix after transposing.
Can you transpose a non-square rectangular matrix?
Yes. Out-of-place transpose handles any matrix shape. Declare a new matrix with swapped dimensions and copy elements as trans[j][i] = mat[i][j]. A 3x4 input produces a 4x3 output.
What is the time complexity of matrix transpose?
O(rows * cols) for both approaches. Every element is visited exactly once during the double loop. Space complexity is O(rows * cols) for out-of-place and O(1) for in-place.
Why does in-place transpose not work for rectangular matrices?
In-place transpose swaps mat[i][j] with mat[j][i] using the same array. For rectangular matrices, the swapped index falls outside the original array bounds, causing memory errors or index exceptions.
Which placement tests include matrix transpose questions?
Matrix problems including transpose, rotation, and diagonal operations appear in Wipro NLTH technical rounds and TCS NQT coding sections. The core logic does not change year to year.
How do I transpose a matrix using NumPy in Python?
Use the .T attribute: mat.T returns the transposed matrix without any looping. Alternatively, numpy.transpose(mat) works the same way. Both run in O(rows * cols) time.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)