C Language Example - Matrix Transposition

C Language Examples

Matrix transpose.

Example

#include <stdio.h> int main() { int a[10][10], transpose[10][10], r, c, i, j; printf("Enter the number of rows and columns of the matrix:"); scanf("%d %d", &r, &c); // Store matrix elements printf("\nEnter matrix elements:\n"); for(i=0; i<r; ++i) for(j=0; j<c; ++j) { printf("Enter element a%d%d:",i+1, j+1); scanf("%d", &a[i][j]); } // Display matrix a[][] */ printf("\nEnter matrix:\n"); for(i=0; i<r; ++i) for(j=0; j<c; ++j) { printf("%d ", a[i][j]); if (j == c-1) printf("\n\n"); } // Transpose for(i=0; i<r; ++i) for(j=0; j<c; ++j) { transpose[j][i] = a[i][j]; } // Display the transposed matrix a printf("\nMatrix after conversion:\n"); for(i=0; i<c; ++i) for(j=0; j<r; ++j) { printf("%d ",transpose[i][j]); if(j==r-1) printf("\n\n"); } return 0; }

The output result is:

输入矩阵的行与列: 2 3

输入矩阵元素:
输入元素 a11: 2
输入元素 a12: 3
输入元素 a13: 4
输入元素 a21: 5
输入元素 a22: 6
输入元素 a23: 4

输入矩阵: 
2  3  4  

5  6  4  


转换后矩阵:
2  5  

3  6  

4  4  

C Language Examples

other extensions