for loop continuous summation, multiplication table code_PHP tutorial

WBOY
Release: 2016-07-21 15:20:02
Original
1026 people have browsed it

The classic example of a for loop is continuous summation: 1+2+3+...+100. After teaching for more than an hour, some students still can't do it. You have to be thoughtful when making programs. Some students kept typing on the keyboard and couldn't get it right. Before doing this summation, we have to think about it. Summation is actually continuous accumulation. When variable $i increases by itself, it must be summed with the previous number. So how to sum with the previous number? We can do a split: treat the number before $i as one item, and add it to $i separately. In the same way, 100 is added to the sum of the previous 99 items, 99 is added to the sum of the previous 98 items...and so on. , 2 plus the previous number 1, then 1 is 1+0. When writing a program, think in reverse, first calculate 0+1=1, then 1+2=3, then 3+3=6...

Copy code The code is as follows:

/*
*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 '
';
// echo $sum.'+'.$i.'=';
echo '=';
echo $sum = $sum+$i;
echo '
';
}
echo $sum;
?>

The echo statement in the middle of the loop body is for testing the process and can be seen more clearly.
The multiplication table below uses a two-layer for loop, which may be more difficult for novices, but it can still be understood if you study patiently and think attentively.
Copy code The code is 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 '';
}
echo '';
}
echo '
'.$j.'x'.$i.'='.$j*$i.'
';
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325157.htmlTechArticleThe classic example of a for loop is continuous summation: 1+2+3+……+100, that’s it After more than an hour, there are still some students who can’t. You have to be thoughtful when doing programs. Some students kept typing on the keyboard and couldn't get it done...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template