Right-angled triangle (left aligned)
📌 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).
No comments yet! You be the first to comment.
