In this tutorial below you can learn about the method to Print Stars Pattern in PHP. These are the questions that are generally asked in the interviews and should be answered. Such problems are usually addressed by people who have a good understanding of the nested loops.
This star pattern program concept can be used to solve in C / C++/Java and other programming languages, the distinction is the application syntax.
1 2 3 4 5 | for ($i = 1; $i <= 5; $i++) { echo "*"; } |
Output: The loop will be run 5 times and the out will be shown as below.
1 | ***** |
1 2 3 4 5 6 | for($i = 1; $i <= 5; $i++) { echo "*"; echo "<br>"; } |
Output: The loop will be run 5 times and the “*” will be printed on every line.
1 2 3 4 5 | * * * * * |
1 2 3 4 5 6 7 8 9 10 11 | for($i = 1; $i <= 5; $i++) { for($j = 1; $j <= 5; $j++) { echo "*"; } echo "<br>"; } |
Output: In the above code, The star(*) will be printed 5 times in a row and the line will be the break and run again.
1 2 3 4 5 | ***** ***** ***** ***** ***** |
1 2 3 4 5 6 7 8 9 10 11 | for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo "*"; } echo "<br>"; } |
Output:
1 2 3 4 5 | * ** *** **** ***** |
1 2 3 4 5 6 7 8 9 10 11 | for ($i = 5; $i >= 1; $i--) { for ($j = $i; $j >= 1; $j--) { echo "*"; } echo "<br>"; } |
Output:
1 2 3 4 5 | ***** **** *** ** * |
1 2 3 4 5 6 7 8 9 10 11 12 | for($i = 1; $i <= 5; $i++) { for($j = 1; $j <= 5; $j++) { if($i == 1 || $i == 5) { echo "*"; } elseif($j == 1 || $j == 5) { echo "*"; } else { echo " "; } } echo "<br>"; } |
Output:
1 2 3 4 5 | ***** * * * * * * ***** |