English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive C Programming Examples
In this example, you will learn how to find the transpose of a matrix in C programming.
To understand this example, you should understand the followingC ProgrammingTopic:
The transpose of the matrix is a new matrix obtained by exchanging rows and columns.
In this program, the user is required to input the number of rows r and the number of columns c. In this program, their values should be less than10.
Then, the user is required to input the elements of the matrix (r * c-order).
Then, the following program calculates the transpose of the matrix and prints it on the screen.
#include <stdio.h> int main() { int a[10][10], transpose[10][10], r, c, i, j; printf("Input rows and columns: "); scanf("%d %d", &r, &c); //Allocate elements to the matrix printf("\nInput matrix elements:\n"); for (i = 0; i < r;) ++i) for (j = 0; j < c;) ++j) { printf("Input element a%d%d: ", i + 1, j + 1); scanf("%d", &a[i][j]); } //Display matrix a[][] printf("\nInput matrix: \n"); for (i = 0; i < r;) ++i) for (j = 0; j < c;) ++j) { printf("%d \t", a[i][j]); if (j == c - 1) printf("\n"); } //Compute the transpose of matrix a for (i = 0; i < r;) ++i) for (j = 0; j < c;) ++j) { transpose[j][i] = a[i][j]; } //Display the transpose of matrix a printf("\nMatrix transpose:\n"); for (i = 0; i < c;) ++i) for (j = 0; j < r;) ++j) { printf("%d ", transpose[i][j]); if (j == r - 1) printf("\n"); } return 0; }
Output Result
Input Rows and Columns: 2 3 Input Matrix Elements: Input Element a11: 1 Input Element a12: 4 Input Element a13: 0 Input Element a21: -5 Input Element a22: 2 Input Element a23: 7 Input Matrix: 1 4 0 -5 2 7 Matrix Transpose: 1 -5 4 2 0 7