Solutions to the exercises

   Sum Example   Computing a sum "; echo "The sum of 10 ... 20 is ". sum(10, 20). "";

// Initialze a product, then repeated multiply it by 1, 2, ..., $n function factorial($n) { $product = 1; for ($k = 1; $k <= $n; $k++) $product *= $k; return $product; }

// For CS Majors: A recursive factorial -- it calls itself instead of using a loop function rFactorial($n) { if ($n == 0) return 1; else return $n * rFactorial($n-1); }

echo "0! is ". factorial(0). ""; echo "5! is ". factorial(5). ""; echo "10! is ". factorial(10). ""; // Go through each letter of the string comparing it to a blank. // If it's blank, add 1 to the counter. function countBlanks($str) { $count = 0; for ($k=0; $k < strlen($str); $k++) if ($str[$k] == ' ') ++$count; return $count; }

echo "'hello world!' has ". countBlanks("hello world!"). " blanks"; echo "' hello world! this is a test ' has ". countBlanks(" hello world! this is a test "). " blanks";

?>  </HTML>