The classic example of a For loop is a continuous summation: 1+2+3+......+100, speaking for one hours, or a classmate will not. Do the procedure to have thought, some students have been knocking on the keyboard, also did not get out. Before we do this sum, we have to think about that summation is actually a continuous summation, and when the variable $i is bound to be summed with the previous number, then how is it summed with the previous number? We can do a split: think of the number of $i before as an item, separate and $i add, similarly, 100 plus the sum of the previous 99 items, 99 plus the previous 98 items and ... And so on, 2 plus the previous number 1, then 1, that 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 the Code code as follows:
/*
*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 '
';
echo $sum. ' + '. $i. ' = ';
echo ' = ';
echo $sum = $sum + $i;
Echo '
';
}
Echo $sum;
?>
The Echo statement in the middle of the loop is designed to test the process and can be seen more clearly.
The following 99 multiplication table uses a two-tier for loop, which may be more difficult for novice learners, but patience, concentration, and understanding.
Copy the Code code as follows:
/*
*file name:99.php
*author:luchanghong
*email:luchanghong@xingmo.com
*time:2011/5/9
*/
Echo '
'; for ($i = 1; $i <10; + + $i) {echo '
'; for ($j = 1; $j <= $i; + + $j) {echo '
'. $j. ' x '. $i. ' = '. $j * $i. ' | '; } Echo '
'; } Echo '
';
?>
The above describes the 99 multiplication table for loop continuous summation, 99 multiplication table code, including the 99 multiplication table aspect of the content, I hope that the PHP tutorial interested friends helpful.