The classic example of a for-loop is a continuous summation: 1+2+3+......+100, for one hours, there are no students. Do the procedure has the thought, some schoolmates always knocks on the keyboard, also did not get out. Before we do this sum, we have to think about that summation is actually a continuous accumulation, when the variable $i since the increase of the number must be with the previous sum, then how to sum up with the previous number? We can do a split: think of the number before $i as an item, separate and $i, and, similarly, 100 plus the sum of the previous 99 and 99 plus the sum of the preceding 98 ... And so on, 2 plus the previous number 1, then 1 is 1+0. In the writing process, is reverse thinking, first calculate 0+1=1, then calculate 1+2=3, then 3+3=6 ...
Copy Code code as follows:
<?php
/*
*file name:1+...+100.php
*author:luchanghong
*email:luchanghong@xingmo.com
*time:2011/5/24
*/
$sum = 0;
$str = ';
for ($i = 0; $i <= + + $i)
{
echo $str. = $i. ' + ';
Echo ' <br> ';
echo $sum. ' + '. $i. ' = ';
echo ' = ';
echo $sum = $sum + $i;
Echo ' <br> ';
}
Echo $sum;
?>
The Echo statement in the middle of the loop body is designed to test the process and can be seen more clearly.
The following 99 multiplication table uses two for loops, perhaps novice feel more difficult, but, patience to study, concentrate on thinking or can read.
Copy Code code as follows:
<?php
/*
*file name:99.php
*author:luchanghong
*email:luchanghong@xingmo.com
*time:2011/5/9
*/
Echo ' <table border=1> ';
for ($i = 1; $i <10 + + $i)
{
Echo ' <tr> ';
for ($j = 1; $j <= $i; + + $j)
{
Echo ' <td> ' $j. ' x ' $i. $j * $i. ' </td> ';
}
Echo ' </tr> ';
}
Echo ' </table> ';
?>