Aims:
for
-loops
with while
-loops
for
-loops versus while
-loopsfor
-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
-loop can always be used in place of a
for
-loop, and vice versa
for
-loop:
for ( $i = 0; $i < 5; $i++ ) { echo "<p>{$i}</p>"; }
while
-loop:
$i = 0; while ( $i < 5 ) { echo "<p>{$i}</p>"; $i++; }
for
-loop:
$number = (int) $_GET['number']; $root = 0; $odd = 1; while ( $number > 0 ) { $number -= $odd; $root++; $odd += 2; } echo "<p>The square root is {$root}</p>";
You deposit 1000 eurines in your Allied Nerdish Bank account. At the end of each year, 10 per cent cumulative interest is added
Year | Deposit | Interest earned |
---|---|---|
1 | 1000 | 100 |
2 | 1100 | 110 |
3 | 1210 | 121 |
4 | 1331 | 133.1 |
5 | 1464.1 |
interest1.html
contains this form:
<form action="interest1.php" method="get"> <input type="text" name="deposit" /> <input type="text" name="interest_rate" /> <input type="text" name="num_years" /> <input type="submit" /> </form>
interest1.php
which outputs the
amount in the user's account if s/he deposits
deposit eurines for num_years
years at an interest rate of interest_rate%
interest2.html
contains this form:
<form action="interest2.php" method="get"> <input type="text" name="deposit" /> <input type="text" name="interest_rate" /> <input type="text" name="desired_deposit" /> <input type="submit" /> </form>
interest2.php
which outputs the
the number of years it will take for the amount in the user's
account to grow to at least desired_deposit
eurines if s/he deposits
deposit eurines at an interest rate of interest_rate%
break
continue
do…while
loop