Write a Program to Find the Transpose of a Matrix

Write a Program to Find the Transpose of a Matrix

Explanation

Transposing a matrix is also known as flipping a matrix where rows become columns and columns become rows,

In other words, lets M[a][b] is a matrix and Transpose of it is M[b][a].

Where,

  • a indicates the rows of the matrix
  • b indicates the number of columns in the matrix

For Example:

transpose of a matrix

This question was asked in the Zoho interview.

by solving this problem, you will also learn about multidimensional array. Check list of coding questions on Array.

Algorithm

  1. Start the Program
  2. Declare the Matrix variables
  3. Get the input for the matrix using loops
  4. Perform the transpose operation ( Similar to swapping)
  5. Print the Transpose of the Matrix.
  6. End the Program

C/C++ Program

Prerequisites:

Code:

You can execute this program using our CSEstack online IDE.

#include<stdio.h>

int main()
{
  int a[3][2],b[2][3], i, j; 
 
  //take user input
  printf("Enter value for matrix: "); 
  for(i=0;i<3;i++)
  {
    for(j=0;j<2;j++) 
      scanf("%d",&a[i][j]);
  }
 
  //print origional matrix
  printf("Matrix:\n"); 
  for(i=0;i<3;i++)
  {
    for(j=0;j<2;j++) 
      printf(" %d ",a[i][j]); 
    printf("\n");
  }
 
  //find the transpose of the matrix
  for(i=0; i<3; i++)
  {
    for(j=0; j<2; j++) 
      b[j][i] = a[i][j];
  }
 
  //print transposed matrix
  printf("Transpose matrix:\n"); 
  for(i=0; i<2; i++)
  {
    for(j=0; j<3; j++) 
    printf(" %d ", b[i][j]); 
    printf("\n");
  }

  return 0;
}

Output:

Enter value for matrix: 

Matrix:
  1  2 
  3  4 
  5  6 

Transpose matrix:
  1  3  5 
  2  4  6 

Just like any for loop, you can also use the while or do-while loop to solve this problem.

You can also this program to find the transpose of a matrix in any other programming language as C/C++, Java or Python. Give it a try.

Leave a Reply

Your email address will not be published. Required fields are marked *