C Program to Transpose a Matrix

4 Min Read

A matrix is defined as a rectangular arrangement of numbers in the form of rows and columns. When the elements in rows and columns of a matrix are exchanged, a new matrix is formed which is known as transpose of the matrix. It carries a great significance in structural dynamics calculation, electrical engineering, mathematics and physics.

Finding the transpose of a matrix in C is a popular tutorial under “array”. It basically gives the idea of matrix inputting, manipulating and outputting using the standard input/output functions of the C language.

The basic logic behind matrix transposition is swapping the elements of row and respective column. After entering all the elements of the matrix, the number of rows and columns are swapped and a loop is started to exchange the elements. The exchanged or newly formed elements are stored as the elements of transposed matrix.

Algorithm to Transpose a Matrix:

Source Code in C to Transpose a Matrix:

#include <stdio.h>
int main()
{
   int a, b, c, d, mat[10][10], trans[10][10]; //declaration of variable
   printf(" Enter the number of rows and columns of matrix: ");
   scanf("%d%d",&a,&b); // inputting order of matrix
   printf(" Enter the elements of matrix \n");
    for( c = 0 ; c < a ; c++ )// loop to input the matrix
   {
      for( d = 0 ; d < b ; d++ )
      {
         scanf("%d",&mat[c][d]);
      }
   }

   for( c = 0 ; c < a ; c++ ) // loop to transpose the matrix
   {
      for( d = 0 ; d < b ; d++ )
      {
         trans[d][c] = mat[c][d];
      }
   }

   printf(" The traspose of entered matrix is:-\n");

   for( c = 0 ; c < b ; c++ ) // loop for printing transposed matrix
   {
      for( d = 0 ; d < a ; d++ )
      {
         printf("%d\t",trans[c][d]);
      }
      printf("\n");
   }

   return 0;
}

When this C program is executed, it asks for the number of rows and columns of the matrix to be transposed. Then, the elements of matrix need to be entered row wise. Finally, the transposed matrix is displayed as console output in standard matrix format following the algorithm aforementioned.

There are other various ways of solving matrix transposition problem in C, such as by using function, pointers, etc. The presented source code is to be compiled in Code::Blocks IDE. If you have any questions regarding the source code or algorithm here, bring them up from the comments section.

Share This Article
Leave a comment

Leave a Reply

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

English
Exit mobile version