Answer to Question #338839 in C++ for Ashir

Question #338839

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-05-09T14:55:17-0400
#include <iostream>
#include <string>

const int SIZE = 4;

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;
}

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) {
      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];
    }
  }

  int** transposed = transpose(matrix);

  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