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

Answers 2

Answer:

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;

Explanation:

Answer:

#include <iostream>

#include <iomanip>

#include <time.h>

using namespace std;

void show(int matrix[4][4]){

   for(int i = 0; i < 4; i++){

       for(int j = 0; j < 4; j++)

           cout<<left<<setw(4)<<matrix[i][j];

       cout<<endl;

   }

}

void swap(int* a, int* b){

   int temp = *a;

   *a = *b;

   *b = temp;

}

int main(){

   int matrix[4][4];

   srand(time(NULL));

   for(int i = 0; i < 4; i++)

       for(int j = 0; j < 4; j++)

           matrix[i][j] = rand() % 101;

   cout<<"Filled with random numbers:\n";

   show(matrix);

   for(int i = 0; i < 4; i++)

       for(int j = i + 1; j < 4; j++)

           swap(&matrix[i][j], &matrix[j][i]);

   cout<<"\nTransposed:\n";

   show(matrix);

   return 0;

}

Explanation:

#include <iostream>

#include <iomanip>

#include <time.h>

using namespace std;

void show(int matrix[4][4]){

   for(int i = 0; i < 4; i++){

       for(int j = 0; j < 4; j++)

           cout<<left<<setw(4)<<matrix[i][j];

       cout<<endl;

   }

}

void swap(int* a, int* b){

   int temp = *a;

   *a = *b;

   *b = temp;

}

int main(){

   int matrix[4][4];

   srand(time(NULL));

   for(int i = 0; i < 4; i++)

       for(int j = 0; j < 4; j++)

           matrix[i][j] = rand() % 101;

   cout<<"Filled with random numbers:\n";

   show(matrix);

   for(int i = 0; i < 4; i++)

       for(int j = i + 1; j < 4; j++)

           swap(&matrix[i][j], &matrix[j][i]);

   cout<<"\nTransposed:\n";

   show(matrix);

   return 0;

}

If you know the answer add it here!

Can't find the answer?

Log in with Google

or

Forgot your password?

I don't have an account, and I want to Register

Choose a language and a region
How much to ban the user?
1 hour 1 day 100 years