# Transpose a matrix

### Write a program to transpose a matrix

e.g.) Input matrix.
1  2  3
4 5 6
7 8 9

Transposed matrix.
1 4 7
2 5 8
3 6 9

#### C++ program to transpose a matrix

`#include <iostream>#include <cstdlib>#include <ctime>using namespace std;int main() {srand(time(0));int m = 3;int n = 3;int** matrix = (int**) calloc(sizeof(int), m);for ( int i = 0; i < m; i++ ) {matrix[i] = (int*) calloc(sizeof(int), n);}// Fill random values in the matrixfor ( int i = 0; i < m; i++ ) {for ( int j = 0; j < n; j++ ) {matrix[i][j] = rand() % 100;}}// Print the matrixfor ( int i = 0; i < m; i++ ) {for ( int j = 0; j < n; j++ ) {cout << matrix[i][j] << " ";}cout << endl;}cout << endl;// Transposefor ( int i = 0; i < m; i++ ) {for ( int j = i + 1; j < n; j++ ) {int tmp = matrix[i][j];matrix[i][j] = matrix[j][i];matrix[j][i] = tmp;}}// Print the transposed matrixcout << "Transposed matrix" << endl;for ( int i = 0; i < m; i++ ) {for ( int j = 0; j < n; j++ ) {cout << matrix[i][j] << " ";}cout << endl;}delete[] matrix;}`

Output:-

`89 33 1092 87 469 33 74Transposed matrix89 92 6933 87 3310 4 74`