Practice 5

Main | Review of Operators | Mathematical Functions | Practice 5 | Solution 5 | HTML Forms | PHP Forms | Practice 6 | Solution 6 | PHP and E-mail | Practice 7 | Solution 7

In math we can take the factorial of an integer by taking the product of its preceding positive integers. So:

1! = 1
2! = 2 * 1 = 2
3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24
5! = 5 * 4 * 3 * 2 * 1 = 120

We could change the notation of the above and replace the exclamation point (!) with a function called factorial such that:

factorial(5) = 5!

and thus:

factorial(5) = 5 * 4 * 3 * 2 * 1 = 120

To complete this exercise you must:

  • Create a file in "public_html/php" called "factorial.php".
  • Be sure that "factorial.php" is viewable from the web.
  • Fill in "factorial.php" with this incomplete code.
  • Define a function which takes in a number $n and returns factorial($n).
  • Call your function on the number 5 and print the result.

For extra credit make a recursive version of your factorial function. Use the following definition:

n! = {n*(n-1)! if n > 1 OR 1 if n = 1

HINTS:

If you are not sure where to start here are some hints for the exercise (these hints are not for the extra credit).

  • Use a loop to define your function
  • Try making your loop count backwards ($i-- instead of $i++)
  • Try defining a variable which you will return and set the the variable equal to one. Then use your loop to multiply it by the descending values of $n.


jfulton [at] member.fsf.org
22 Aug 2013