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

  1. 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
  2. Then we print stars in each row.
  3. 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 to n.
  • Remaining columns should be filled with spaces.

Example (matrix for n = 5):

Row \ Col12345
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 to n.
  • Inner loop ($j) โ†’ prints each column.
  • Condition:
    • If $j >= $n - $i + 1 โ†’ print star "* ".
    • Else โ†’ print space " ".

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.

Leave a Reply

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