Aims:
for
-loopsfor
-loopfor
-loop in general:
for (expr1; expr2; expr3)
{
zero, one or more statements
}
$current_year = (int) date('Y'); for ( $year = 1948; $year <= $current_year; $year++ ); { if ( $year % 4 == 0 ) { echo "<p>{$year} was an Olympic year</p>"; } }
for
-loops are
off-by-one errors, where the programmer writes a
loop that executes one too many, or one too few, times
for ( $k = 0; $k < 5; $k++ )
for ( $k = 0; $k <= 5; $k++ )
for ( $k = 1; $k < 5; $k++ )
for ( $k = 1; $k <= 5; $k++ )
Assuming $m
and $n
contain non-negative
integers and that $n >= $m
,
how many iterations will there be of the following loops?
for ( $i = $m; $i < $n; $i++ )
{
echo "<p>{$i}</p>";
}
for ( $i = $m; $i <= $n; $i++ )
{
echo "<p>{$i}</p>";
}
for
-loopsfor
-loop,
$current_year = (int) date('Y'); for ( $year = 1948; $year <= $current_year; $year += 4 ) { echo "<p>{$year} was an Olympic year</p>"; }
The version below is also correct but the previous version is better than this version. Why?
for ( $year = 1948; $year <= (int) date('Y'); $year += 4 ) { echo "<p>{$year} was an Olympic year</p>"; }
for
-loop that echoes the numbers
from 36 to 1 (inclusive) in that order
for
-loop that never terminates (an
infinite loop), forever printing consecutive
integers starting from 0
for
-loop header
$number = (int) $_GET['number']; $total = 0; for ( $i = 1; $i <= $number; $i++ ) { $total += $i; } echo "<p>The sum of the numbers from 1 to {$number} is {$total}</p>";
for
-loop when you have
a counter that moves from start to end with constant
increments made at the end of the loop body