C++ Online Compiler
Example: Transpose Matrix Without Function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Transpose Matrix Without Function #include <iostream> using namespace std; int main() { // Step 1: Declare dimensions and matrices int rows, cols; cout << "Enter number of rows: "; cin >> rows; cout << "Enter number of columns: "; cin >> cols; int matrix[rows][cols]; // Original matrix int transpose[cols][rows]; // 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 (optional, for verification) cout << "\nOriginal Matrix:" << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << matrix[i][j] << " "; } cout << endl; } // Step 4: Compute the transpose // The element at matrix[i][j] goes to transpose[j][i] for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { transpose[j][i] = matrix[i][j]; } } // Step 5: Print the transposed matrix cout << "\nTransposed Matrix:" << endl; for (int i = 0; i < cols; ++i) { // Note: iterate up to cols for rows here for (int j = 0; j < rows; ++j) { // Note: iterate up to rows for columns here cout << transpose[i][j] << " "; } cout << endl; } return 0; }
Output
Clear
ADVERTISEMENTS