HomePROGRAMMESTAR PATTERN PROGRAMMERight-angled triangle (right aligned) Star Pattern

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.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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