Solutions to the exercises

[article] [edit page] [discussion] [history]

From Humanitarian-FOSS Project Development Site

<?php
/*
 * Created on Feb 18, 2008
 *
 * Solutions to in-class exercises.
 * 
 */
?>
<HTML>
  <HEAD>
    <TITLE>Sum Example</TITLE>
  </HEAD>
  <BODY>
    <H4>Computing a sum</h4>
    <?php
       // Initialize a sum to 0, then repeated add m, (m+1), ..., n to it.
       function sum($m, $n) {
          $sum = 0;
          for ($k = 0; $k <= $n; $k++) { 
             $sum += $k;
          }
          return $sum;
       }

       $x = 1;
       $y = 10;
       echo "The sum of $x ... $y is " . sum($x, $y) . "<BR>";
       echo "The sum of 10 ... 20 is " . sum(10, 20) . "<BR>";

       // 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) . "<BR>";
       echo "5! is " . factorial(5) . "<BR>";
       echo "10! is " . factorial(10) . "<BR>";
     
       // 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<BR>";
       echo "' hello world! this is a test ' has " . countBlanks(" hello world! this is a test ") . " blanks<BR>";

    ?>
  </BODY>
</HTML>

Personal tools