C++ Online Compiler
Example: Display Lower Triangular Matrix in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Display Lower Triangular Matrix #include <iostream> #include <vector> // Using vector for dynamic arrays, common in modern C++ #include <iomanip> // For std::setw to format output int main() { // Step 1: Define the size of the square matrix const int SIZE = 3; // Step 2: Initialize a sample square matrix // This matrix will be used to demonstrate the lower triangular form std::vector<std::vector<int>> matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; std::cout << "Original Matrix:" << std::endl; for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) { std::cout << std::setw(3) << matrix[i][j]; // Use setw for alignment } std::cout << std::endl; } std::cout << std::endl; // Add a blank line for readability std::cout << "Lower Triangular Matrix:" << std::endl; // Step 3: Iterate through the matrix to display the lower triangular form for (int i = 0; i < SIZE; ++i) { // Loop through rows for (int j = 0; j < SIZE; ++j) { // Loop through columns // Step 4: Check if the current element is part of the lower triangle // An element matrix[i][j] is in the lower triangle if j <= i if (j <= i) { std::cout << std::setw(3) << matrix[i][j]; // Print the actual element } else { std::cout << std::setw(3) << " "; // Print spaces for elements above the diagonal } } std::cout << std::endl; // Move to the next line after each row } return 0; }
Output
Clear
ADVERTISEMENTS