Skip to content
Advertisement

“Numeric triangle” – Convert FOR to WHILE in PHP

I am trying to create a numeric triangle using a WHILE loop.

This is a numeric triangle created using FOR:

Numeric triangle 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 "&nbsp;&nbsp;&nbsp;";
    }
    for($k=1; $k<=$m; $k++)  {
        echo $k ."&nbsp";
    }
    for($c=$m; $c>1; $c--) {
        echo $c-1 ."&nbsp";
    }
    echo "<br>";
    $m++;
}

I want to create the numeric triangle using WHILE

It looks like this:

numerictriangle-while


My attempt at WHILE

$i=1;
$j=1;
$k=1;
$m=1;
while($i<=$n) {
    while($j<=$n-1) {
        echo "&nbsp;&nbsp;&nbsp;";
        j++;
    }
    while($k<=$m)  {
        echo $k ."&nbsp";
        k++;
    }
    $c=$m;
    while($c>1) {
        echo $c-1 ."&nbsp";
        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 "&nbsp;&nbsp;&nbsp;";
       $j++;
    }

    // second loop
    $k=1;
    while ($k<=$m) {
        echo $k ."&nbsp";
        $k++;
    }

    // third loop
    $c=$m;
    while ($c>1) {
        echo $c-1 ."&nbsp";
        $c--;
    }

    echo "<br>";
    $m++;
    $i++;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement