Transpose of a matrix in c

Transposing a matrix is a process of exchanging rows with columns of a matrix. In C, transposing a matrix can be performed using a nested loop.

 

The following steps demonstrate how to transpose a matrix in C:

 

First, we need to define the matrix that we want to transpose. We can use a two-dimensional array for this purpose. For example, the matrix "A" can be defined as:

 

int A[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

 

Next, we can create another matrix "B" to store the transposed matrix. We can use the same size as matrix A.

 

int B[3][3];

 

We can then use nested loops to iterate through the matrix A and assign each element to the corresponding element in matrix B. We need to swap the row and column indices while assigning the elements.

 

for (int i = 0; i < 3; ++i)

{

for (int j = 0; j < 3; ++j)

{

B[j][i] = A[i][j];

}

}

 

Finally, we can print the transposed matrix B using nested loops.

 

printf("Transposed matrix:\n");

for (int i = 0; i < 3; ++i)

{

for (int j = 0; j < 3; ++j)

{

printf("%d ", B[i][j]);

}

printf("\n");

}

 

The above code will output the following transposed matrix:

 

1 4 7

2 5 8

3 6 9

 

In summary, transposing a matrix involves swapping the rows and columns of a matrix. In C, we can use nested loops to perform the transposition.

 

// c program to find the transpose of a matrix OR c program to find transpose of a matrix

#include <stdio.h>

 

int main() {

  int matrix[10][10], transpose[10][10], row, col;

 

  printf("Enter the number of rows and columns of the matrix: ");

  scanf("%d %d", &row, &col);

 

  printf("Enter the elements of the matrix:\n");

  for(int i=0; i<row; i++) {

    for(int j=0; j<col; j++) {

      scanf("%d", &matrix[i][j]);

    }

  }

 

  printf("\nOriginal Matrix:\n");

  for(int i=0; i<row; i++) {

    for(int j=0; j<col; j++) {

      printf("%d\t", matrix[i][j]);

    }

    printf("\n");

  }

 

  // Finding transpose of matrix

  for(int i=0; i<row; i++) {

    for(int j=0; j<col; j++) {

      transpose[j][i] = matrix[i][j];

    }

  }

 

  printf("\nTranspose of Matrix:\n");

  for(int i=0; i<col; i++) {

    for(int j=0; j<row; j++) {

      printf("%d\t", transpose[i][j]);

    }

    printf("\n");

  }

 

  return 0;

}

 

In this program, we take the input of a matrix from the user and then find its transpose by interchanging the rows and columns. Finally, we display both the original matrix and its transpose.

Transpose of a matrix in c Transpose of a matrix in c Reviewed by Vision Academy on March 08, 2023 Rating: 5

No comments:

CheckOut

Powered by Blogger.