C++ Online Compiler
Example: Transpose Matrix With Function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Transpose Matrix With Function #include <iostream> using namespace std; // Function to compute and store the transpose of a matrix // Note: In C++, when passing 2D arrays to functions, the number of columns // must be specified. For dynamically sized matrices, you'd typically use // std::vector<std::vector<int>> or pass pointers. For simplicity, we'll // use fixed maximum sizes or C-style VLA (Variable Length Array) which // is a GNU extension or C99 feature, not standard C++. // For standard C++, we often use templates or std::vector. // Here, we'll pass dimensions and use dynamic allocation or fixed size // to demonstrate the concept. Let's use fixed max sizes for simplicity for this tutorial. const int MAX_SIZE = 10; // Maximum size for rows and columns void getTranspose(int originalMatrix[MAX_SIZE][MAX_SIZE], int rows, int cols, int transposedMatrix[MAX_SIZE][MAX_SIZE]) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { transposedMatrix[j][i] = originalMatrix[i][j]; } } } // Function to print a matrix void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int rows, int cols) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << matrix[i][j] << " "; } cout << endl; } } int main() { // Step 1: Declare dimensions and matrices int rows, cols; cout << "Enter number of rows (max " << MAX_SIZE << "): "; cin >> rows; cout << "Enter number of columns (max " << MAX_SIZE << "): "; cin >> cols; if (rows > MAX_SIZE || cols > MAX_SIZE) { cout << "Error: Dimensions exceed maximum allowed size." << endl; return 1; } int matrix[MAX_SIZE][MAX_SIZE]; // Original matrix int transpose[MAX_SIZE][MAX_SIZE]; // Transposed matrix // Step 2: Input elements into the original matrix cout << "Enter elements of the matrix:" << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << "Enter element matrix[" << i << "][" << j << "]: "; cin >> matrix[i][j]; } } // Step 3: Print the original matrix cout << "\nOriginal Matrix:" << endl; printMatrix(matrix, rows, cols); // Step 4: Compute the transpose using the function getTranspose(matrix, rows, cols, transpose); // Step 5: Print the transposed matrix cout << "\nTransposed Matrix:" << endl; printMatrix(transpose, cols, rows); // Note: Pass cols, then rows for dimensions return 0; }
Output
Clear
ADVERTISEMENTS