C++ Online Compiler
Example: Matrix Transpose using Class in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Transpose using Class #include <iostream> class Matrix { private: int rows; int cols; int** data; // Pointer to an array of pointers (for dynamic 2D array) public: // Constructor: Initializes matrix dimensions and allocates memory Matrix(int r, int c) : rows(r), cols(c) { data = new int*[rows]; // Allocate memory for row pointers for (int i = 0; i < rows; ++i) { data[i] = new int[cols]; // Allocate memory for columns in each row } } // Destructor: Deallocates memory to prevent memory leaks ~Matrix() { for (int i = 0; i < rows; ++i) { delete[] data[i]; // Delete columns for each row } delete[] data; // Delete row pointers } // Method to read elements into the matrix void readElements() { std::cout << "Enter matrix elements (" << rows << "x" << cols << "):" << std::endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << "Enter element at (" << i + 1 << "," << j + 1 << "): "; std::cin >> data[i][j]; } } } // Method to display the matrix void displayElements() { std::cout << "Matrix (" << rows << "x" << cols << "):" << std::endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << data[i][j] << "\t"; } std::cout << std::endl; } } // Method to display the transpose of the matrix void displayTranspose() { std::cout << "Transpose of Matrix (" << cols << "x" << rows << "):" << std::endl; for (int j = 0; j < cols; ++j) { // Iterate through columns of original matrix for (int i = 0; i < rows; ++i) { // Iterate through rows of original matrix std::cout << data[i][j] << "\t"; // Access element [row][col] } std::cout << std::endl; } } }; int main() { int r, c; // Step 1: Get matrix dimensions from the user std::cout << "Enter number of rows: "; std::cin >> r; std::cout << "Enter number of columns: "; std::cin >> c; // Step 2: Create a Matrix object Matrix myMatrix(r, c); // Step 3: Read elements into the matrix myMatrix.readElements(); // Step 4: Display the original matrix myMatrix.displayElements(); // Step 5: Display the transpose of the matrix myMatrix.displayTranspose(); return 0; }
Output
Clear
ADVERTISEMENTS