Right-angled triangle (right aligned) Star Pattern
๐ Pattern (for n = 5)
*
* *
* * *
* * * *
* * * * *
Notice: stars are aligned to the right side.
โ PHP Program (Right-Aligned Triangle)
<?php
// Number of rows
$n = 5;
// Outer loop for rows
for ($i = 1; $i <= $n; $i++) {
// Print spaces first
for ($j = 1; $j <= $n - $i; $j++) {
echo " "; // two spaces for alignment
}
// Print stars
for ($k = 1; $k <= $i; $k++) {
echo "* ";
}
// Move to next line
echo "\n";
}
?>
๐ Explanation
for ($j = 1; $j <= $n - $i; $j++)โ prints spaces before stars.- Row 1 โ 4 spaces + 1 star
- Row 2 โ 3 spaces + 2 stars
- Row 3 โ 2 spaces + 3 stars
- Row 4 โ 1 space + 4 stars
- Row 5 โ 0 space + 5 stars
- Then we print stars in each row.
- Finally, move to the next line.
๐ Matrix Visualization
We treat it as a 5 ร 5 grid (matrix).
- Row index โ which row we are printing.
- Column index โ where to place
"*"or" "(space).
Rule:
- For row
i, stars should start from column(n - i + 1)up ton. - Remaining columns should be filled with spaces.
Example (matrix for n = 5):
| Row \ Col | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| 1 | * | ||||
| 2 | * | * | |||
| 3 | * | * | * | ||
| 4 | * | * | * | * | |
| 5 | * | * | * | * | * |
โ PHP Program (Matrix Approach)
<?php
// Number of rows
$n = 5;
// Loop through rows
for ($i = 1; $i <= $n; $i++) {
// Loop through columns
for ($j = 1; $j <= $n; $j++) {
if ($j >= $n - $i + 1) {
echo "* "; // print star
} else {
echo " "; // print space
}
}
echo "\n"; // new line after each row
}
?>
๐ Explanation
- Outer loop (
$i) โ goes from row 1 ton. - Inner loop (
$j) โ prints each column. - Condition:
- If
$j >= $n - $i + 1โ print star"* ". - Else โ print space
" ".
- If
This way we simulate the matrix filling logic row by row.
๐น Output for n = 5
*
* *
* * *
* * * *
* * * * *
๐ This is the Right-Aligned Triangle Pattern in PHP.
No comments yet! You be the first to comment.
