Perform Matrix Transpose in C

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
2D arrays

What You’ll Learn

The transpose AT flips a matrix so rows become columns: (AT)ij = Aji, and an m × n matrix becomes n × m. This tutorial covers the index swap, a second buffer, a live preview, worked C examples (2×3 and 3×3), edge cases, and O(m·n) complexity.

Definition

(AT)ij = Aji

Swap row and column indices at every entry.

Shape Flip

m×n → n×m

Height and width swap; 2×3 becomes 3×2.

Second Buffer

out[cols][rows]

Copy into a new array so you do not overwrite source data.

Index Swap

out[i][j]=a[j][i]

One assignment expresses the whole idea.

Live Preview

2×3 → 3×2

See A and AT instantly in the browser.

Double Flip

(AT)T = A

Transpose twice to recover the original.

Introduction

The transpose of a matrix A is written AT. Its entries satisfy (AT)ij = Aji: row and column indices are swapped.

So if A has m rows and n columns, AT has n rows and m columns. In C interviews you allocate a second buffer and copy with transposed[i][j] = matrix[j][i].

Why it matters?

Transpose is a gentle but precise 2D-array drill: swapped dimensions, careful loop bounds, and a clear reason to use a second buffer before discussing in-place square tricks.

Key Highlights

Rows → Columns

First row becomes first column.

m×n → n×m

Output shape flips with the indices.

Copy Buffer

Safest for rectangles and learners.

O(m·n)

Touch each entry once to fill AT.

In short: allocate out[cols][rows], then set out[i][j] = matrix[j][i] for all valid i, j.

📝 Problem & Approach

Given a matrix of size rows × cols, build its transpose of size cols × rows and print both.

c
/* A is 2×3 → A^T is 3×2
 * A =  1 2 3      A^T = 1 4
 *      4 5 6             2 5
 *                        3 6
 * out[i][j] = a[j][i]
 */

Inputs & Outputs

ItemTypeDescription
matrix2D arrayOriginal; logical size rows × cols.
transposed / out2D arrayResult; size cols × rows.
rows, colsintsMust match the filled slice of the array.

Minimal workflow

Pseudocode
function transpose(matrix, rows, cols, out):   // out is cols × rows
    for i from 0 to cols - 1:
        for j from 0 to rows - 1:
            out[i][j] ← matrix[j][i]

Method comparison

ApproachWhenNotes
Second buffer (this page)Any shapeSafest; required for non-square in fixed arrays
In-place swapsSquare onlySwap a[i][j] with a[j][i] for i < j
Addition / subtractionSame shape opsNo index swap; different problem

⚡ Quick Reference

GoalPattern
One celltransposed[i][j] = matrix[j][i];
Output shapecols × rows when input is rows × cols
Loop boundsi < cols, j < rows
Double transpose(A^T)^T = A
CostO(m · n) time; O(m · n) for output buffer

📋 Transpose vs Other Matrix Ops

Transpose rearranges indices — it does not add, subtract, or multiply entries.

Transpose
Aji → out

This page — swap indices

Addition
Aij+Bij

Same shape; no flip

Multiply
Σ Aik Bkj

Dot products; triple nest

Interview tip
copy first

Second buffer before in-place

Context

When This Problem Shows Up

Reach for transpose when rows need to become columns, or when preparing factors for related linear-algebra steps.

  1. Interview staple

    Tests 2D indexing and swapped loop bounds.

  2. Data layout

    Convert row-major tables to column-oriented views.

  3. Linear algebra prep

    Building ATA or related forms conceptually.

  4. Rectangle vs square

    Show why non-square needs a new shape buffer.

  5. Not for in-place rectangles

    Changing shape usually requires separate storage.

Key benefit: one clear index-swap rule that proves you understand both shape changes and safe buffering.

🔮 Live Preview

Uses the same 2×3 sample as Example 1. Press the button to see A and AT.

Matches the first C program’s numbers.

Live result
Press “Transpose sample”.

Examples Gallery

Two complete C programs — a rectangle (2×3 → 3×2) and a square 3×3. Click View Output to reveal sample console results.

📚 Getting Started

Allocate the flipped shape, then copy with swapped indices.

Example 1 — Transpose a 2×3 Matrix

Classic layout: store the original in a fixed upper-bound array, pass real rows and cols, build transposed[cols][rows].

c
#include <stdio.h>

#define MAX 10

void transpose_matrix(int matrix[MAX][MAX], int rows, int cols) {
    int transposed[MAX][MAX];
    int i, j;

    for (i = 0; i < cols; ++i) {
        for (j = 0; j < rows; ++j) {
            transposed[i][j] = matrix[j][i];
        }
    }

    printf("Original (%d x %d):\n", rows, cols);
    for (i = 0; i < rows; ++i) {
        for (j = 0; j < cols; ++j) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }

    printf("Transposed Matrix (%d x %d):\n", cols, rows);
    for (i = 0; i < cols; ++i) {
        for (j = 0; j < rows; ++j) {
            printf("%d\t", transposed[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    int matrix[MAX][MAX] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    int rows = 2;
    int cols = 3;

    transpose_matrix(matrix, rows, cols);

    return 0;
}

How It Works

The assignment transposed[i][j] = matrix[j][i] is the whole idea. Loop ranges follow the swapped dimensions: i runs cols times, j runs rows times.

📈 Practical Patterns

Same index swap on a square matrix — output shape matches the input.

Example 2 — Transpose a 3×3 Matrix

First row 1 2 3 becomes the first column of the result. Still uses a separate buffer (simplest and safest for learners).

c
#include <stdio.h>

#define N 3

void transpose_square(int a[N][N], int out[N][N]) {
    int i, j;
    for (i = 0; i < N; ++i) {
        for (j = 0; j < N; ++j) {
            out[i][j] = a[j][i];
        }
    }
}

void print_matrix(const char *title, int m[N][N]) {
    int i, j;
    printf("%s\n", title);
    for (i = 0; i < N; ++i) {
        for (j = 0; j < N; ++j) {
            printf("%d ", m[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    int a[N][N] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int t[N][N];

    transpose_square(a, t);

    print_matrix("A", a);
    printf("\n");
    print_matrix("A^T", t);

    return 0;
}

How It Works

For square matrices, out is the same shape as a. In-place transpose is possible for squares but easier to get wrong; two buffers keep the lesson clear.

🧠 How the Algorithm Transposes a Matrix

1

Allocate output shape

Result has cols rows and rows columns when the input is rows × cols.

Shape
2

Copy with swapped indices

For each i in 0 .. cols-1 and j in 0 .. rows-1, assign out[i][j] = matrix[j][i].

Swap
3

Print

Outer loop over rows of the transpose (cols), inner over columns (rows).

Display
=

AT ready

For the 2×3 sample, first column of AT is 1 2 3 from the first row of A.

🔎 Worked Walkthrough — First Column of AT

Trace how the first row of the 2×3 sample becomes the first column of the transpose.

SourceValueDestination
A[0][0]1AT[0][0]
A[0][1]2AT[1][0]
A[0][2]3AT[2][0]

So the first column of AT is 1, 2, 3. The second source row fills the second column the same way.

Use Cases

Where transpose thinking shows up beyond the interview prompt.

1. Index-Swap Practice

Master [j][i] vs [i][j] carefully.

Example: double nested copy.

2. Shape Awareness

Prove you notice m×n becoming n×m.

Example: 2×3 sample.

3. Buffer Discipline

Motivate a second array before in-place talk.

Example: rectangle case.

4. Sanity Check

Transpose twice and compare to A.

Example: (AT)T = A.

5. Square Follow-up

Discuss optional in-place diagonal swaps.

Example: after the 3×3 demo.

6. Contrast Matrix Ops

Show transpose is rearrange, not arithmetic.

Example: after addition/multiply pages.

Pro Tip: say “m×n becomes n×m, then out[i][j] = a[j][i]” before writing any loops.

Advantages

Why the second-buffer approach earns interview points.

  1. 1. Works for Any Shape

    Rectangles and squares use the same copy rule.

  2. 2. Hard to Clobber Source

    A separate buffer avoids overwriting values you still need.

  3. 3. Clear Complexity

    O(m·n) time with an obvious output array.

  4. 4. Easy to Verify

    First row of A should match first column of AT.

Pro Tip: mention in-place square transpose only as a follow-up after the correct buffered solution.

Usage Tips

Small habits that keep transpose code clean in interviews.

  1. 1. State the New Shape First

    Say m×n → n×m before coding.

  2. 2. Match Loop Bounds to out

    Outer i < cols, inner j < rows for the buffered form.

  3. 3. Keep rows/cols Honest

    They must match the filled portion of the array.

  4. 4. Dry-Run One Row

    Confirm row 0 of A becomes column 0 of AT.

  5. 5. Size MAX Safely

    Ensure MAX ≥ max(rows, cols) for both dimensions when using one square buffer.

Pro Tip: the walkthrough table for the first column of AT is the fastest way to lock in the index swap before typing.

Common Pitfalls

Mistakes that commonly break transpose solutions in C.

  1. 1. Wrong Loop Bounds

    Looping i < rows when writing into a cols × rows result.

    → Bound i by cols and j by rows for the buffered form.

  2. 2. Writing out[i][j] = a[i][j]

    That copies without flipping — not a transpose.

    → Always use out[i][j] = a[j][i].

  3. 3. In-Place on a Rectangle

    Shape changes; there is no same-array home for every entry.

    → Use a second buffer for non-square matrices.

  4. 4. Lying rows/cols Counts

    Wrong sizes print garbage or walk past filled data.

    → Keep counts consistent with the initializer.

  5. 5. MAX Too Small

    Fixed buffers must fit both dimensions of both matrices.

    → Ensure MAX ≥ max(rows, cols).

Edge Cases

Keep dimensions honest and buffers large enough.

Bounds

rows and cols

They must match the slice of the array you filled. Wrong counts produce garbage or logic errors.

MAX

Fixed array size

MAX must be at least max(rows, cols) for both dimensions of both matrices when using one big square buffer.

1×n

Row / column vectors

A 1×n row becomes an n×1 column (and vice versa) with the same rule.

Square

In-place option

Only for n×n: swap across the diagonal with i < j; still optional for interviews.

Check

Double transpose

Applying transpose twice should recover A exactly.

Print

Print loop sizes

When printing AT, outer count is cols and inner is rows.

🔄 Input / Output

To experiment, change the numbers inside matrix and adjust rows and cols so they stay consistent with how much of the array you actually use.

SampleResult highlight
2×3 demoAT is 3×2 with columns [1,2,3] and [4,5,6]
3×3 demoAT first column is 1 4 7

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Trace the second column

  • Use the 2×3 sample
  • Confirm AT column 1 is 4 5 6

2. Double transpose

  • Transpose the 3×3 result again
  • Verify you recover A

3. 3×2 rectangle

  • Start from a 3×2 matrix
  • Produce a 2×3 result

4. Optional in-place

  • For square only, swap a[i][j] with a[j][i]
  • Only after the buffered version works

Notes

  • Rule: (AT)ij = Aji; sizes swap from m×n to n×m.
  • Copy into transposed[i][j] = matrix[j][i] with matching loop bounds.
  • Double transpose: (AT)T = A.
  • Non-square matrices need a second buffer; shape changes.

Quick Takeaway: flip the shape to n×m, then fill with out[i][j] = a[j][i] — prefer a second buffer until you are ready for in-place square tricks.

⏱️ Time and Space Complexity

TaskTimeExtra space
Transpose m × n (buffered)O(m · n)O(m · n) for the output buffer
Wrap Up

🎉 Conclusion

Matrix transpose flips rows into columns: m×n becomes n×m, and each entry moves via out[i][j] = a[j][i]. Master the 2×3 and 3×3 samples so you can reason about buffers and optional in-place square variants later.

Practice both examples above, then continue to finding the maximum value in an array for a 1D warm-up.

Shape flips, then out[i][j] = matrix[j][i] — and (AT)T = A.

💡 Best Practices

✅ Do

  • State m×n → n×m before coding
  • Use a second buffer for rectangles
  • Write out[i][j] = a[j][i] consistently
  • Keep rows/cols consistent with the data
  • Quote O(m·n) time for the classic pass

❌ Don’t

  • Forget to swap loop bounds for the output
  • Copy with matching indices (no flip)
  • Force in-place transpose on non-square matrices
  • Mis-size MAX for both dimensions
  • Skip verifying the first row → first column

Key Takeaways

Knowledge Unlocked

Five things to remember about matrix transpose in C

Implement it the interview-friendly way.

5
Core concepts
02

Shape

m×n → n×m

Flip
2 03

Buffer

Copy out

Safe
ij 04

Assign

out[i][j]=a[j][i]

Code
O 05

Cost

O(m·n)

Analysis

❓ Frequently Asked Questions

Take every row of the original matrix and write it as a column of a new matrix (or swap row index with column index at each entry).
It has 3 rows and 2 columns. In general an m×n matrix becomes n×m.
The entry at row i, column j of A^T equals the entry at row j, column i of A. In symbols: (A^T)_ij = A_ji (with your book’s index convention).
In general a non-square matrix changes shape, so you usually need a second buffer. For a square n×n matrix you can swap across the diagonal in place with care.
So each assignment transposed[i][j] = matrix[j][i] does not overwrite data you still need from the original matrix.
You touch every element once to fill the transpose: O(m·n) time for an m×n matrix, with O(m·n) space for the output array.
You get the original back: (A^T)^T = A. That is a useful sanity check.
If the input is rows × cols, loop i over cols and j over rows when writing transposed[i][j] = matrix[j][i].

Did you Know? 🔊

The transpose flips a matrix across its diagonal: rows become columns. If A is m × n, then AT is n × m, and (AT)T = A.

Continue to Maximum Value of an Array

Learn how to find the largest element in a 1D array with a simple scan in C.

Maximum of an Array tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful