For loop continuous summation, 9-9 multiplication table code. A typical example of a for loop is continuous summation: 1 + 2 + 3 + ...... + 100. after talking for more than an hour, some students still don't. Some people have to think about the program. some people keep typing on the keyboard, and the classic example of for loop is continuous summation: 1 + 2 + 3 + ...... + 100. after talking for more than an hour, some students still don't. I had to think about the program. some people kept typing on the keyboard and didn't figure it out. Before proceeding to this summation, we should consider that the summation is actually continuous accumulation. when the variable $ I is auto-incrementing, it must sum with the previous number, so how can we sum up the previous number? We can make a split: consider the number before $ I as one item and add it to $ I separately. Similarly, 100 adds the sum of the previous 99 items, 99 adds 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, it is reverse thinking. First calculate 0 + 1 = 1, then calculate 1 + 2 = 3, then 3 + 3 = 6 ......
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 used to test the process and can be seen more clearly.
The following 9-9 multiplication table uses a two-layer for loop, which may be more difficult for new users. However, you can still learn it with patience and focus on thinking.
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'
'. $ J. 'x'. $ I.' = '. $ j * $ I .' | ';}Echo'
';}Echo'
';
?>
Bytes ...... + 100. after talking for more than an hour, some students still don't. I had to think about the program. some people kept typing on the keyboard and didn't figure it out...