Example problems
<?php
/*
*
* Exercise:
* Write a PHP script that a contains function for printing sequences starting at 0, ending at n
* that are divisible by m. For example if n is 20 and m is 3, the function should print:
* 0, 3, 6, 9, 12, 15, 18. If m were 5, it should print 0, 5, 10, 15, 20.
*/
?>
<HTML>
<HEAD>
<TITLE>Function Example</TITLE>
</HEAD>
<BODY>
<H4>Counting to N by M with a function</h4>
<?php
/*
* printSequence() prints the sequence from 0 to $n by $m.
*/
function printSequence($n, $m) {
for ($k = 0; $k <= $n; $k+=$m) {
echo "$k ";
}
echo "<BR>";
}
printSequence(20, 5);
printSequence(10, 2);
printSequence(40, 3);
printSequence(100, 10);
printSequence(50, 25);
/*
* printSequence2() prints either an increasing or decreasing sequence.
* The default is increasing in which case $n > 0.
* For decreasing sequences, $n < 0.
*/
function printSequence2($n, $m, $incr=TRUE) {
if ($incr == TRUE) {
for ($k = 0; $k <= $n; $k+=$m)
echo "$k ";
}
else {
for ($k = 0; $k >= $n; $k-=$m)
echo "$k ";
}
echo "<BR>";
}
printSequence2(20, 5);
printSequence2(-20, 5, FALSE);
?>
</BODY>
</HTML>