Matrix Transpose in C

Level 5235 keystrokes

Transposes the 2x3 matrix {{1, 2, 3}, {4, 5, 6}} into a 3x2 matrix by copying element [i][j] to [j][i], then prints it row by row: 1 4, 2 5, 3 6.

C code

// A 2x3 matrix: 2 rows of 3 columns
1int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
// The transpose swaps the dimensions, so it is 3x2
2int t[3][2];
// Visits every element of m, row by row
3for (int i = 0; i < 2; i++) {
4 for (int j = 0; j < 3; j++) {
// Row i, column j of m becomes row j, column i of t
5 t[j][i] = m[i][j];
6 }
7}
// Prints t: 3 rows of 2 values
8for (int i = 0; i < 3; i++) {
9 for (int j = 0; j < 2; j++) {
// Prints each element followed by a space
10 printf("%d ", t[i][j]);
11 }
// Ends the row; the rows printed are 1 4, 2 5 and 3 6
12 printf("\n");
13}

Output

1 4 
2 5 
3 6 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 13
  • [× 10
  • ]× 10
  • +× 8
  • {× 7
  • }× 7
  • ,× 6
  • (× 6
  • )× 6
  • =× 6

More C examples at level 5

← C typing practice