For loop continuous summation, 99 multiplication table code _php tips

Source: Internet
Author: User
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> ';
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.