C++ Online Compiler
Example: Upper Triangular Matrix (User Input) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Upper Triangular Matrix (User Input) #include <iostream> #include <vector> // Required for dynamic arrays (vectors) using namespace std; int main() { int rows, cols; // Step 1: Get matrix dimensions from the user cout << "Enter the number of rows: "; cin >> rows; cout << "Enter the number of columns: "; cin >> cols; // Step 2: Declare a 2D vector (dynamic array) to store the matrix // This allows for matrices of arbitrary size determined at runtime vector<vector<int>> matrix(rows, vector<int>(cols)); // Step 3: Get matrix elements from the user cout << "Enter the elements of the matrix (" << rows << "x" << cols << "):\n"; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << "Enter element at [" << i << "][" << j << "]: "; cin >> matrix[i][j]; } } cout << "\nOriginal Matrix:\n"; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << matrix[i][j] << "\t"; // Using tab for better alignment } cout << endl; } cout << "\nUpper Triangular Matrix:\n"; // Step 4: Iterate and display the upper triangular form for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (j < i) { cout << "0\t"; // Print 0 for elements below the main diagonal } else { cout << matrix[i][j] << "\t"; // Print original element } } cout << endl; } return 0; }
Output
Clear
ADVERTISEMENTS