4.5: Factorial Function
( \newcommand{\kernel}{\mathrm{null}\,}\)
Mathematically, we define the factorial as a function on a non-negative integer as
n!=n(n−1)(n−2)⋯3⋅2⋅1
or the product of all of the numbers from itself down to 1. There are a number of ways to program this function as we will see. One way is
uses a for
loop and we will see the details of this in Chapter XXX. The for
loop first assigns i
the value 1 then executes the lines, then sets the value to 2, then executes the block, and so on until i
is n
. Since prod starts as 1, this multiplies prod by every integer between 1 and n
, and thus is the factorial. The result in prod
is returned.
For example, we can call the factorial function with an example like
Exercise
Try calling the factorial with a few other integers. Include 0 and negative numbers as well.