π Pattern Example (for n = 5)
*
**
***
****
*****
β Step-by-Step (DSA Approach)
- Understand the problem
- Rows =
n - In each row
iβ print exactlyistars. - Simple nested loop problem.
- Rows =
- 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 - 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)
- Input
n= number of rows - Traverse row-wise (outer loop)
- For each column (inner loop):
- If
col <= rowβ print"*" - Else β print
" "(space)
- If
π» 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=1 β j=1 (*) j=2..5 ( ) β *
i=2 β j=1 (*) j=2 (*) j=3..5 ( ) β **
i=3 β j=1 (*) j=2 (*) j=3 (*) j=4..5 ( ) β ***
i=4 β j=1..4 (*) j=5 ( ) β ****
i=5 β j=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 ngrid, decides star/space at each cell (more structured, useful for complex patterns).
