I am trying to create a numeric triangle using a WHILE loop.
This is a numeric triangle created using FOR:
This is my existing FOR code
$m=1; $n=9; $z=9;
for($i=1; $i<=$n; $i++) {
    for($j=$i; $j<=$n-1; $j++) {
       echo "   ";
    }
    for($k=1; $k<=$m; $k++)  {
        echo $k ." ";
    }
    for($c=$m; $c>1; $c--) {
        echo $c-1 ." ";
    }
    echo "<br>";
    $m++;
}
I want to create the numeric triangle using WHILE
It looks like this:
My attempt at WHILE
$i=1;
$j=1;
$k=1;
$m=1;
while($i<=$n) {
    while($j<=$n-1) {
        echo "   ";
        j++;
    }
    while($k<=$m)  {
        echo $k ." ";
        k++;
    }
    $c=$m;
    while($c>1) {
        echo $c-1 ." ";
        c--;
    }
    echo "<br>";
    $m++;
    $i++
}
$n is inputed
I don’t know where to place $c=$m in last
Or maybe I have make a mistake??
Advertisement
Answer
It’s better to put each counter just before it’s own loop. Generally speaking you can convert any for loop to a while loop if you note this schematics:
for loops are usually something like this:
for ([init]; [condition]; [increment]) {
    /* the main code */
}
while loops are usually something like this:
[init];
while ([condition]) {
    /* the main code */
    [increment];
}
so you only need to change place of some parts of the code, which result something like
$m=1; $n=9; $z=9;
// the main loop
$i=1;
while ($i <= $n) {
    // first loop
    $j=$i;
    while ($j <= $n-1) {
       echo "   ";
       $j++;
    }
    // second loop
    $k=1;
    while ($k<=$m) {
        echo $k ." ";
        $k++;
    }
    // third loop
    $c=$m;
    while ($c>1) {
        echo $c-1 ." ";
        $c--;
    }
    echo "<br>";
    $m++;
    $i++;
}

