考试Qn:将while while循环转换为for循环(PHP)

Recently, my exams got over. My last exam was based on PHP. I got the following question for my exam:

"Convert the following script using for loop without affecting the output:-"

<?php
 //Convert into for loop
 $x = 0;
 $count = 10;
 do
 {
  echo ($count. "<BR>");
  $count = $count - 2;
  $x = $x + $count; 
 }
 while($count < 1)
 echo ($x);
?>

Please help me as my computer sir is out of station and I am really puzzled by it.

Well, If I understand well, You have to use "for" loop, instead of "do...while", but the printed text must not change.

Try:

$count = 10;
$x = 0;
$firstRun = true;
for(; $count > 1 || $firstRun;) {
    $firstRun = false;
    echo ($count . "<BR>");
    $count -= 2;
    $x = $x + $count; 
}
echo ($x);

By the way loop is unnecessary, because $count will be greater than 1 after the first loop, so the while will get false.

EDIT

  • $firstRun to avoid infiniteLoop
  • $count in loop

EDIT

  • Fixed code for new requirement
  • Removed unnecessary code

Hmmm I don't know if your teacher wanted to own you... but the do{} will execute only once since $count is never < 1.

The output of your teacher's code is:
10
8

I presume there was a mistake in the code and the while would be while($count > 1) which would make more sense (since it's weird to ask for a loop to output only 10 8) and would result in this output:
10
8
6
4
2
20

Then a good for() loop would have been :

$x = 0;
$count = 10;
for($i = $count; $i > 1; $i -= 2)
{
    $count -= 2;
    echo $i . "<br>";
    $x += $count;
}
echo $x;

Which will output the same values. If you can, ask your teacher for this, and comment the answer ^^ ahahah