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.
#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;
}
Comments
Leave a comment