C++ Online Compiler
Example: Display Upper Triangular Matrix in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Display Upper Triangular Matrix #include <iostream> // Required for input/output operations #include <vector> // Required for std::vector (dynamic arrays) #include <iomanip> // Required for std::setw (output formatting) int main() { // Step 1: Define the size of the square matrix int size = 3; // For a 3x3 matrix // Step 2: Initialize the matrix with some values // Using a 2D vector for dynamic sizing and ease of use std::vector<std::vector<int>> matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // You can also get user input for the matrix elements: /* std::cout << "Enter " << size * size << " elements for the " << size << "x" << size << " matrix:\n"; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { std::cout << "Enter element at (" << i + 1 << "," << j + 1 << "): "; std::cin >> matrix[i][j]; } } */ // Step 3: Display the original matrix (optional, for comparison) std::cout << "Original Matrix:\n"; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { std::cout << std::setw(3) << matrix[i][j]; // setw(3) for alignment } std::cout << std::endl; } std::cout << "\n"; // Step 4: Display the Upper Triangular Matrix std::cout << "Upper Triangular Matrix:\n"; for (int i = 0; i < size; ++i) { // Iterate through rows for (int j = 0; j < size; ++j) { // Iterate through columns // Condition for upper triangular part: column index >= row index (j >= i) if (j >= i) { std::cout << std::setw(3) << matrix[i][j]; // Print the actual element } else { std::cout << std::setw(3) << 0; // Print '0' for elements below the main diagonal } } std::cout << std::endl; // Move to the next line after each row } return 0; }
Output
Clear
ADVERTISEMENTS