Pattern 1:
* * * * *
* * * *
* * *
* *
*
* * * * *
* * * *
* * *
* *
*
$input = 5; for ($i = 0; $i < $input; $i++) { for ($j = $i; $j < $input; $j++) { echo '* '; } echo PHP_EOL; }
So what happens here is -
Here take a note that we are looping both the for loops in row-wise and the column-wise pattern.
In the first for loop, we are iterating for 5 times ($i < $input). It will loop like this.
$i=0 -> $i=1 -> $i=2 -> $i=3 -> $i=4
Then in the inner loop, we will assign $i to $j so that the inner loop will iterate depending upon the outer loop. Then we added $j < $input to make sure that assigned value to $j should always be less than $input.
Then, we added echo '* '; (some space after * to beautify patterns for visual purpose)
And finally, after inner for loop, we added PHP_EOL to make sure that whenever inner loop ends then the next stars(*) will print in the next line.
So our loop will print like following-
First Iteration:
for ($i = 0; $i < 5; $i++) { for ($j = $i; $j < 5; $j++) { // $j = 0, $j = 1, $j = 2, $j = 3, $j = 4 echo '* '; } echo PHP_EOL; }// output
* * * * *
Second iteration:
for ($i = 1; $i < 5; $i++) { for ($j = $i; $j < 5; $j++) { // $j = 1, $j = 2, $j = 3, $j = 4 echo '* '; } echo PHP_EOL; }// output
* * * *
Third Iteration:
for ($i = 2; $i < 5; $i++) { for ($j = $i; $j < 5; $j++) { // $j = 2, $j = 3, $j = 4 echo '* '; } echo PHP_EOL; }// output
* * *
Fourth Iteration:
for ($i = 3; $i < 5; $i++) { for ($j = $i; $j < 5; $j++) { // $j = 3, $j = 4 echo '* '; } echo PHP_EOL; }// output
* *
Fifth Iteration:
for ($i = 4; $i < 5; $i++) { for ($j = $i; $j < 5; $j++) { // $j = 4 echo '* '; } echo PHP_EOL; }// output
*
So Final output becomes-
* * * * *
* * * *
* * *
* *
*
No comments:
Post a Comment