spectatorx spectatorx - 4 months ago 29
PHP Question

Image patterns with nested loops

Currently i'm practicing some exercises with loops and nested loops. I already created a code to "draw" such pattern:

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


and to make it i wrote such code:

$n = 5;

for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j <= $n; $j++) {
if ($j <= $i) {
echo '*';
}
echo '<br>';
}
}


Now i'm trying to figure out how to "draw" such pattern:

* 2 3 4 5
* * 3 4 5
* * * 4 5
* * * * 5
* * * * *
* * * * *
* * * * 5
* * * 4 5
* * 3 4 5
* 2 3 4 5


The only thing i concluded so far is to use something similar as in previous code but i'm really out of idea how to implement it. Could you help me on this?

Answer
$n = 5;

for ($i = 0; $i < $n; $i++) {
    for ($j = 0; $j <= $n; $j++) {
        if ($j <= $i) {
            echo '*';
        }
        else {
            echo $j;
        }
    }
    echo '<br>';
}
for ($i = $n; $i > 0; $i--) {
    for ($j = 0; $j <= $n; $j++) {
        if ($j <= $i) {
            echo '*';
        }
        else {
            echo $j;
        }
    }
    echo '<br>';
}

See the difference in incremental and decremental loops