fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5. int arr[3][4] = {
  6. {1, 2, 3, 4},
  7. {5, 6, 7, 8},
  8. {9, 10, 11, 12}
  9. };
  10.  
  11. int row = sizeof(arr)/sizeof(arr[0]);
  12. int col = sizeof(arr[0])/sizeof(arr[0][0]);
  13.  
  14. cout << "Original Matrix:" << endl;
  15. for(int i = 0; i < row; i++) {
  16. for(int j = 0; j < col; j++) {
  17. cout << arr[i][j] << " ";
  18. }
  19. cout << endl;
  20. }
  21.  
  22. cout << "Transposed Matrix:" << endl;
  23. // Switch the loop order: Columns become the outer loop
  24. for(int j = 0; j < col; j++) {
  25. for(int i = 0; i < row; i++) {
  26. // Access by [i][j] but in column-major order
  27. cout << arr[i][j] << " ";
  28. }
  29. cout << endl;
  30. }
  31.  
  32. return 0;
  33. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Original Matrix:
1 2 3 4 
5 6 7 8 
9 10 11 12 
Transposed Matrix:
1 5 9 
2 6 10 
3 7 11 
4 8 12