Answer to Question #326765 in C++ for naqibullah

Question #326765

Write a C++ program that creates a 2D array having 4 rows and 4 columns. Then, ask the user to input values for the 2D array or matrix. After that, the program should calculate transpose of a matrix. Transpose is basically calculated by changing rows of matrix into columns and columns into rows. After calculating, display the final matrix?



1
Expert's answer
2022-04-11T07:44:57-0400
#include <iostream>
#include <string>


const int SIZE = 4;


// Allocate memory for matrix
int** createMatrix() {
  int** matrix = new int*[SIZE];
  for (int i = 0; i < SIZE; ++i) {
    // Allocate memory for each row
    matrix[i] = new int[SIZE];
  }
  return matrix;
}


// Free the memory used by a matrix
void freeMatrix(int** matrix) {
  for (int i = 0; i < SIZE; ++i) {
    delete[] matrix[i];
  }
  delete[] matrix;
}


int** transpose(int** matrix) {
  int** transposed = createMatrix();
  for (int i = 0; i < SIZE; ++i) {
    for (int j = 0; j < SIZE; ++j) {
      transposed[i][j] = matrix[j][i];
    }
  }
  return transposed;
}


void printMatrix(int** matrix) {
  for (int i = 0; i < SIZE; ++i) {
    for (int j = 0; j < SIZE; ++j) {
      // Separate values in a row with spaces,
      // separate rows with line breaks
      std::cout << matrix[i][j] << (j == SIZE - 1 ? '\n' : ' ');
    }
  }
}


int main() {
  int** matrix = createMatrix();
  std::cout << "Enter matrix values:\n";
  for (int i = 0; i < SIZE; ++i) {
    for (int j = 0; j < SIZE; ++j) {
      std::cin >> matrix[i][j];
    }
  }


  // Transpose
  int** transposed = transpose(matrix);


  // Print out
  std::cout << "Transposed matrix:\n";
  printMatrix(transposed);
  freeMatrix(matrix);
  freeMatrix(transposed);
  return 0;
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS