for loop continuous sum multiplication table code
- 2020-05-12 02:25:35
- OfStack
A classic example of an for cycle is a continuous summation: 1+2+3+... Plus 100. I've been talking for over an hour, but some of you can't. Do the program to have thought, some students 1 straight hit the keyboard, did not get out. So before we do this sum, we have to think about 1, so the sum is really just a continuous sum, so when the variable $i is going to be increasing by itself it's going to be summing over the previous number, so how do we sum over the previous number? We can do a split: take the number before $i as a single term, and add it to $i alone. Similarly, 100 plus the sum of the previous 99 terms, 99 plus the sum of the previous 98 terms... And so on, 2 plus the previous number, 1, so what about 1, that's 1 plus 0. When you're writing a program, you're thinking in reverse. You start with 0+1=1, then 1+2=3, then 3+3=6...
The echo statement in the middle of the loop body is for testing the procedure and can be seen more clearly.
The Times table 99 below USES a two-layer for cycle, which may be difficult for beginners, but you can still understand it with patience and concentration.
<?php
/*
*file name: 1+...+100.php
*author: luchanghong
*email: luchanghong@xingmo.com
*time: 2011/5/24
*/
$sum = 0;
$str = '';
for($i = 0 ; $i <= 100 ; ++$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 for testing the procedure and can be seen more clearly.
The Times table 99 below USES a two-layer for cycle, which may be difficult for beginners, but you can still understand it with patience and concentration.
<?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>';
?>