We have a 4 x 4 two dimensional array. Fill it with random values from 1 to 100. Write a code to take transpose of the matrix. The following array is shown as an example:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
BECOMES
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
const int m = 4, n = 4;
int arr[4][4];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
arr[i][j] = rand() % 100;
cout << "Random matrix: \n";
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cout << arr[i][j] << " ";
cout << endl;
}
for (int i = 0; i < m; i++)
for (int j = 0; j < i; j++)
{
int tmp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = tmp;
}
cout << endl;
cout << "Transponse of the matrix: \n";
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cout << arr[i][j] << " ";
cout << endl;
}
}
Comments
Leave a comment