PHP Program to Print Star Pattern
for loops in PHP to print star patterns, for example: for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo "*"; } echo "\n"; } prints a right-angled triangle of stars.Examples
How to Think About It
Algorithm
Code
<?php $rows = 5; for ($i = 1; $i <= $rows; $i++) { for ($j = 1; $j <= $i; $j++) { echo "*"; } echo "\n"; } ?>
Dry Run
Let's trace printing 3 rows of stars through the code
Start outer loop with i=1
Inner loop runs j=1 to 1, prints '*' once, then newline
Outer loop i=2
Inner loop runs j=1 to 2, prints '**', then newline
Outer loop i=3
Inner loop runs j=1 to 3, prints '***', then newline
| i (row) | j (stars printed) | Output this row |
|---|---|---|
| 1 | 1 | * |
| 2 | 2 | ** |
| 3 | 3 | *** |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to the number of rows, deciding how many lines to print.
Step 2: Inner loop prints stars
The inner for loop prints stars equal to the current row number without moving to a new line.
Step 3: Newline after each row
After printing stars for a row, echo "\n" moves the cursor to the next line for the next row.
Alternative Approaches
<?php $rows = 5; $i = 1; while ($i <= $rows) { $j = 1; while ($j <= $i) { echo "*"; $j++; } echo "\n"; $i++; } ?>
<?php $rows = 5; for ($i = 1; $i <= $rows; $i++) { echo str_repeat("*", $i) . "\n"; } ?>
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs n times and the inner loop runs up to n times, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space, only variables for counters, so space complexity is O(1).
Which Approach is Fastest?
Using str_repeat is more concise and can be faster in practice, but all approaches have the same O(n^2) time complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clear control over printing stars |
| Nested while loops | O(n^2) | O(1) | Alternative loop style |
| str_repeat function | O(n^2) | O(1) | Simpler code, potentially faster |