Transpose a Matrix in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Transpose a Matrix in C: Program to Find Matrix Transpose

šŸ“‘ On this page:
  • Introduction
  • C Program to Transpose a Matrix
  • Sample Output
  • Program Explanation
  • Algorithm
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • What is matrix transpose and why it is used
  • How to transpose a matrix using a 2D array
  • How to handle both square and rectangular matrices
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to transpose a matrix.

The transpose of a matrix is obtained by interchanging its rows and columns. If a matrix has dimensions r Ɨ c, its transpose will have dimensions c Ɨ r.

šŸ’” Key Point: In a transposed matrix, the element at position (i, j) in the original matrix moves to position (j, i) in the transposed matrix.

Matrix transposition is used in many real-world applications, such as:

  • Image Processing: Rotating images (transpose + flip)
  • Data Science: Converting data format (rows to columns)
  • Computer Graphics: Matrix transformations
  • Linear Algebra: Solving systems of equations

Visual Example

For a 2Ɨ3 matrix:

Original Matrix (2Ɨ3):

[1  2  3]
[4  5  6]

Transposed Matrix (3Ɨ2):

[1  4]
[2  5]
[3  6]

C Program to Transpose a Matrix

#include <stdio.h>

int main() {
    int rows, cols, i, j;
    
    // Ask user for matrix dimensions
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);
    
    // Declare original and transposed matrices
    int matrix[rows][cols];
    int transpose[cols][rows];
    
    // Read elements into the original matrix
    printf("\nEnter %d elements:\n", rows * cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("matrix[%d][%d] = ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Transpose the matrix (swap rows and columns)
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }
    
    // Display original matrix
    printf("\n=== Original Matrix (%dƗ%d) ===\n", rows, cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
    
    // Display transposed matrix
    printf("\n=== Transposed Matrix (%dƗ%d) ===\n", cols, rows);
    for(i = 0; i < cols; i++) {
        for(j = 0; j < rows; j++) {
            printf("%d\t", transpose[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

Sample Output

Enter the number of rows: 2
Enter the number of columns: 3

Enter 6 elements:
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6

=== Original Matrix (2Ɨ3) ===
1	2	3
4	5	6

=== Transposed Matrix (3Ɨ2) ===
1	4
2	5
3	6

Example with a Square Matrix:

Enter the number of rows: 3
Enter the number of columns: 3

Enter 9 elements:
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
matrix[2][0] = 7
matrix[2][1] = 8
matrix[2][2] = 9

=== Original Matrix (3Ɨ3) ===
1	2	3
4	5	6
7	8	9

=== Transposed Matrix (3Ɨ3) ===
1	4	7
2	5	8
3	6	9

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int rows, cols; — dimensions of the matrix
    • int i, j; — loop counters
  3. Declare Matrices:
    • int matrix[rows][cols]; — original matrix
    • int transpose[cols][rows]; — transposed matrix (dimensions are swapped)
  4. Read Matrix: Uses nested loops to read elements into the original matrix.
  5. Transpose Operation: The nested loops iterate through the original matrix and assign matrix[i][j] to transpose[j][i], effectively swapping rows and columns.
  6. Display Matrices: Prints both the original and transposed matrices.
  7. Return: return 0; indicates successful program execution.

šŸ“ Note: The transposed matrix has swapped dimensions. If the original matrix is rows Ɨ cols, the transposed matrix is cols Ɨ rows.

Algorithm to Transpose a Matrix

Step-by-step algorithm:

  1. Start
  2. Read the number of rows (r) and columns (c)
  3. Read r Ɨ c elements into the matrix
  4. Create a transpose matrix of size c Ɨ r
  5. For i = 0 to r-1:
    • For j = 0 to c-1:
      • transpose[j][i] = matrix[i][j]
  6. Print the original matrix
  7. Print the transposed matrix
  8. End

In-Place Transpose for Square Matrices (No Extra Space)

For square matrices, we can transpose in-place without using an extra matrix:

#include <stdio.h>

int main() {
    int n, i, j, temp;
    
    printf("Enter the size of the square matrix: ");
    scanf("%d", &n);
    
    int matrix[n][n];
    
    printf("\nEnter %d elements:\n", n * n);
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // In-place transpose for square matrix
    for(i = 0; i < n; i++) {
        for(j = i + 1; j < n; j++) {
            // Swap matrix[i][j] with matrix[j][i]
            temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
    
    printf("\n=== Transposed Matrix (In-Place) ===\n");
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

Sample Output:

Enter the size of the square matrix: 3

Enter 9 elements:
1 2 3
4 5 6
7 8 9

=== Transposed Matrix (In-Place) ===
1	4	7
2	5	8
3	6	9

How In-Place Transpose Works

  • Only iterates over the upper triangle of the matrix (i < j)
  • Swaps matrix[i][j] with matrix[j][i]
  • The diagonal elements (i == j) remain unchanged
  • Time Complexity: O(n²)
  • Space Complexity: O(1) — no extra matrix needed

Time and Space Complexity

Method Time Complexity Space Complexity
Using Extra Matrix O(r Ɨ c) O(r Ɨ c)
In-Place (Square Only) O(n²) O(1)

šŸ’» Practice Exercise

Challenge 1: Write a program to transpose a matrix without using a second array (for any matrix, not just square).

Challenge 2: Transpose a matrix and then print the sum of the transposed matrix.

šŸ” Click to Show Solution for Challenge 1
#include <stdio.h>

int main() {
    int rows, cols, i, j;
    
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);
    
    int matrix[rows][cols];
    
    printf("\nEnter %d elements:\n", rows * cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Display transpose by printing columns as rows
    printf("\n=== Transposed Matrix (%dƗ%d) ===\n", cols, rows);
    for(i = 0; i < cols; i++) {
        for(j = 0; j < rows; j++) {
            printf("%d\t", matrix[j][i]);
        }
        printf("\n");
    }
    
    return 0;
}

Frequently Asked Questions

1. What is the transpose of a matrix?

The transpose of a matrix is obtained by interchanging rows and columns. The element at position (i, j) in the original matrix moves to position (j, i) in the transposed matrix.

2. How do you transpose a matrix in C?

Use nested loops to copy matrix[i][j] to transpose[j][i]. The transposed matrix will have dimensions swapped (columns Ɨ rows).

3. Can I transpose a matrix without using extra space?

Yes, for square matrices, you can transpose in-place by swapping elements across the diagonal. For rectangular matrices, you need extra space.

4. What happens to the dimensions when a matrix is transposed?

If the original matrix is r Ɨ c, the transposed matrix is c Ɨ r. The number of rows and columns are swapped.

5. What is the use of matrix transposition in real life?

Matrix transposition is used in image processing (rotating images), data science (pivot tables), computer graphics, and solving systems of linear equations.

šŸ’” Tip: Transposing a matrix twice returns the original matrix. This property is useful in many mathematical operations.

šŸ“– Related Tutorials

  • Sum of Diagonal Elements in Matrix
  • Matrix Addition in C
  • Matrix Multiplication in C
  • More Array Assignments

Previous Topic: -->> Sum of Diagonal Elements in Matrix   ||   Next topic: -->> Matrix Multiplication in C


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.