Right-angled triangle (left aligned)

Right-angled triangle (left aligned)

📌 Pattern Example (for n = 5)

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

✅ Step-by-Step (DSA Approach)

  1. Understand the problem
    • Rows = n
    • In each row i → print exactly i stars.
    • Simple nested loop problem.
  2. Break into Algorithm INPUT: n (number of rows) FOR i from 1 to n: FOR j from 1 to i: print "*" Move to new line
  3. DSA Concept Used
    • Iteration (loops)
    • Matrix-like thinking → treat it as a 2D structure:
      • Outer loop = rows
      • Inner loop = columns

💻 PHP Implementation

<?php
function printLeftTriangle($n) {
    // Outer loop for rows
    for ($i = 1; $i <= $n; $i++) {
        // Inner loop for printing stars
        for ($j = 1; $j <= $i; $j++) {
            echo "*";
        }
        // Move to the next line
        echo PHP_EOL;
    }
}

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

📊 Dry Run for n=5

  • i=1*
  • i=2**
  • i=3***
  • i=4****
  • i=5*****

✅ Correct output.


👉 This is the optimal DSA approach (time complexity O(n²), space O(1)).

Would you like me to also show you the matrix approach (where we treat it as filling a 2D grid with * and spaces)? That’s sometimes asked in interviews.

You said:

with matrix also

ChatGPT said:

Perfect 👍
You want the Matrix Approach for the Left-Aligned Right-Angled Triangle in PHP.


📌 Matrix Thinking

Instead of directly printing with nested loops,
we visualize this as an n x n matrix (2D grid):

For n = 5 → Matrix looks like this:

Row 1: * _ _ _ _
Row 2: * * _ _ _
Row 3: * * * _ _
Row 4: * * * * _
Row 5: * * * * *

(_ means blank space)


✅ Algorithm (DSA Matrix Formulation)

  1. Input n = number of rows
  2. Traverse row-wise (outer loop)
  3. For each column (inner loop):
    • If col <= row → print "*"
    • Else → print " " (space)

💻 PHP Code (Matrix Approach)

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

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

📊 Dry Run (n=5)

i=1j=1 (*) j=2..5 ( ) → *    
i=2j=1 (*) j=2 (*) j=3..5 ( ) → **   
i=3j=1 (*) j=2 (*) j=3 (*) j=4..5 ( ) → ***  
i=4j=1..4 (*) j=5 ( ) → ****  
i=5j=1..5 (*) → *****  

✅ Output:

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

⚡ Difference between Normal Loop vs Matrix Approach:

  • Normal loop → only prints stars (inner loop up to i).
  • Matrix approach → considers full n x n grid, decides star/space at each cell (more structured, useful for complex patterns).
No comments yet! You be the first to comment.

Leave a Reply

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