Aims:
while
-loops
for unbounded repetition
foreach
-loops are used to visit each element in
an array and execute the same block of statements
for each element
for
-loops are most commonly used for
bounded repetition, where
the number of times the block of statements is executed
is known in advance
while
-loops are most commonly used for
unbounded repetition, where
the number of times the block of statements is executed
is not known in advance
while
-loopwhile
-loop:
while ( Boolean expression )
{
zero, one or more statements
}
while
-loop exampleroot.html
contains this form:
<form action="root.php" method="get"> <input type="text" name="number" /> <input type="submit" /> </form>The next slide shows
root.php
, which computes the square
root of the user's number using the above method
root.php
$number = (int) $_GET['number']; $root = 0; $odd = 1; while ( $number > 0 ) { $number -= $odd; $root++; $odd += 2; } echo "<p>The square root is {$root}</p>";
$number = (int) $_GET['number']; $root = 0; $odd = 1; while ( $number >= 0 ) { $number -= $odd; $root++; $odd += 2; } echo "<p>The square root is {$root}</p>";
$number = (int) $_GET['number']; $root = 0; $odd = 1; while ( $number != 0 ) { $number -= $odd; $root++; $odd += 2; } echo "<p>The square root is {$root}</p>";
$number = (int) $_GET['number']; $residue = $number; $root = 0; $odd = 1; while ( $number > 0 ) { $residue -= $odd; $root++; $odd += 2; } echo "<p>The square root of {$number} is {$root}</p>";
shift.html
contains this form:
<form action="shift.php" method="get"> <input type="text" name="duration" /> <input type="submit" /> </form>This allows the user to enter the duration (secs) of his/her shift at the local factory
$job_lengths = array(127, 195, 3012,…);
while
-loop,
write shift.php
which says how many of
the jobs will get finished during the user's shift,
assuming they are tackled in the order given