Home > Software engineering >  How to write triangle with stars in Php. (*) I want to do it with while
How to write triangle with stars in Php. (*) I want to do it with while

Time:07-28

I did this with a "for" loop. How can I write this with while. Thank you for your help. I just started learning PHP.

for ($a=0; $a <=10 ; $a  ) { 
    for ($y=0; $y <= $a ; $y  ) { 
        echo "*";
    }
    echo "<br>";
}
for ($a=10; $a >=1 ; $a--) { 
    for ($y=1; $y <= $a ; $y  ) { 
        echo "*";
    }
    echo "<br>";
}

CodePudding user response:

The trick to rewriting a for statement to a while statement is extracting the incrementer initialization ($a = 0) and the incrementation ($a ) itself.

So

for ($a=0; $a <=10 ; $a  )

becomes

$a = 0;
while ($a <=10) {
    $a  ;
}

Result

$a = 0;

while ($a <=10) {
    $y = 0;
    while ($y <= $a) { 
        echo "*";
        $y  ;
    }
    echo "<br>";
    $a  ;
}

$a = 10;

while ($a >=1) { 
    $y = 1;
    while ($y <= $a) { 
        echo "*";
        $y  ;
    }
    echo "<br>";
    $a--;
}

CodePudding user response:

for ($i=10; $i<80; $i =4) {
  // do something
}

is equivalent to:

$i=10
while ($i<80) {
  // do something
   $i =4;
}
  • Related