Inverted right-angled triangle
- Normal Approach (using nested loops)
- 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):
* * * * *
* * * *
* * *
* *
*
No comments yet! You be the first to comment.
