HomePROGRAMMESTAR PATTERN PROGRAMMEInverted right-angled triangle

Inverted right-angled triangle

Inverted right-angled triangle
  1. Normal Approach (using nested loops)
  2. Matrix Approach (using 2D array)

✅ 1. Normal Approach (Nested Loops)

<?php
$rows = 5;  // Number of rows

for ($i = $rows; $i >= 1; $i--) {
    for ($j = 1; $j <= $i; $j++) {
        echo "* ";
    }
    echo "\n";  // new line
}
?>

🔹 Output (for $rows = 5):

* * * * * 
* * * * 
* * * 
* * 
* 

✅ 2. Matrix Approach.

<?php
function printInvertedLeftTriangleMatrix($n) {
    // Loop through rows
    for ($i = 1; $i <= $n; $i++) {
        // Loop through columns (matrix style)
        for ($j = 1; $j <= $n; $j++) {
            if ($j <= ($n - $i + 1)) {
                echo "*";
            } else {
                echo " "; // fill remaining with spaces
            }
        }
        echo PHP_EOL;
    }
}

// Example usage
$n = 5;
printInvertedLeftTriangleMatrix($n);
?>

🔹 Output (for $rows = 5):

* * * * * 
* * * * 
* * * 
* * 
* 

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *