C++ Online Compiler
Example: Print Lower Triangular Matrix in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Print Lower Triangular Matrix #include <iostream> #include <vector> // Using vector for dynamic array, but fixed-size array works too #include <iomanip> // For std::setw to format output int main() { // Step 1: Define the matrix dimensions int rows = 3; int cols = 3; // Step 2: Initialize the matrix (you can take user input here) std::vector<std::vector<int>> matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Step 3: Print the original matrix (optional, for comparison) std::cout << "Original Matrix:\n"; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << std::setw(3) << matrix[i][j]; } std::cout << std::endl; } std::cout << std::endl; // Step 4: Print the lower triangular matrix std::cout << "Lower Triangular Matrix:\n"; for (int i = 0; i < rows; ++i) { // Iterate through rows for (int j = 0; j < cols; ++j) { // Iterate through columns if (i >= j) { // Check if element is on or below the main diagonal std::cout << std::setw(3) << matrix[i][j]; } else { // Element is above the main diagonal std::cout << std::setw(3) << " "; // Print spaces for alignment } } std::cout << std::endl; // Move to the next line after each row } return 0; }
Output
Clear
ADVERTISEMENTS