Breaking

Programs to print * pattern in ascending order

Pattern 2:

*
*  *
*  *  *
*  *  *  *
*  *  *  *  *

$input = 5;

for ($i = 0; $i < $input; $i++) {
    for ($j = 0; $j <= $i; $j++) {
        echo '*  ';
    }
    echo PHP_EOL;
}

So what happens here is -

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 0 to $j so that the inner loop will iterate depending upon the condition $j <= $i. This $j <= $i always make sure that whatever the value of $j it should always be less than OR equal to $i because we are arranging pattern in increasing order.

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 step by step like following-

First Iteration:
for ($i = 0; $i < 5; $i++) {
    for ($j = 0; $j <= 0; $j++) { // $j = 0
        echo '*  ';
    }
    echo PHP_EOL;
}
// output
*

Second iteration:
for ($i = 1; $i < 5; $i++) {
    for ($j = 0; $j <= 1; $j++) { // $j = 0, $j = 1
        echo '*  ';
    }
    echo PHP_EOL;
}
// output
*  *

Third Iteration:
for ($i = 2; $i < 5; $i++) {
    for ($j = 0; $j <= 2; $j++) { // $j = 0, $j = 1, $j = 2
        echo '*  ';
    }
    echo PHP_EOL;
}
// output
*  *  *

Fourth Iteration:
for ($i = 3; $i < 5; $i++) {
    for ($j = 0; $j <= 3; $j++) { // $j = 0, $j = 1, $j = 2, $j = 3
        echo '*  ';
    }
    echo PHP_EOL;
}
// output
*  *  *  *

Fifth Iteration:
for ($i = 4; $i < 5; $i++) {
    for ($j = 0; $j <= 4; $j++) { // $j = 0, $j = 1, $j = 2, $j = 3, $j = 4
        echo '*  ';
    }
    echo PHP_EOL;
}
// output
*  *  *  *  *

So Final output becomes-

*
*  *
*  *  *
*  *  *  *
*  *  *  *  *


No comments:

Post a Comment