C++ Online Compiler
Example: Matrix Transpose using Separate Array in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Transpose using Separate Array #include <iostream> using namespace std; int main() { // Step 1: Define matrix dimensions int rows, cols; cout << "Enter the number of rows for the matrix: "; cin >> rows; cout << "Enter the number of columns for the matrix: "; cin >> cols; // Step 2: Declare original and transpose matrices int originalMatrix[rows][cols]; int transposeMatrix[cols][rows]; // Dimensions are swapped for transpose // Step 3: Get input for the original matrix cout << "\nEnter elements for the original matrix:" << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << "Enter element originalMatrix[" << i << "][" << j << "]: "; cin >> originalMatrix[i][j]; } } // Step 4: Print the original matrix cout << "\nOriginal Matrix (" << rows << "x" << cols << "):" << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << originalMatrix[i][j] << " "; } cout << endl; } // Step 5: Perform the transpose operation for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { transposeMatrix[j][i] = originalMatrix[i][j]; } } // Step 6: Print the transposed matrix cout << "\nTransposed Matrix (" << cols << "x" << rows << "):" << endl; for (int i = 0; i < cols; ++i) { // Note: iterate up to cols for rows of transpose for (int j = 0; j < rows; ++j) { // Note: iterate up to rows for cols of transpose cout << transposeMatrix[i][j] << " "; } cout << endl; } return 0; }
Output
Clear
ADVERTISEMENTS