INTRODUCTION
LESSONS
MORE PHP
|
Task Fourteen - N Factorial
This program uses a recursive function.
- Recursive functions re-use their own code.
- They first test to see if the recursion should continue.
- After this test, the function re-uses itself.
Factorial N works like this ...
- Factorial 5 is the same as 5 * 4 * 3 * 2 * 1
- Factorial 0 is defined as 1.
- Factorial N is defined as N * Factorial(N - 1).
Here is a screen shot of the program.

Here is the program code.
<?php
// -----------------------------------------------------------------
function nfact($n)
{
if ($n == 0)
{
return 1;
}
else
{
return $n * nfact($n - 1);
}
}
// -----------------------------------------------------------------
// ===== INPUT =====================================================
echo "\n\nPlease enter a whole number ... ";
$num = trim(fgets(STDIN));
// =================================================================
// ===== PROCESS - Determing the factorial of the input number =====
$output = "\n\nFactorial " . $num . " = " . nfact($num) . "\n\n";
// =================================================================
// ===== OUTPUT ====================================================
echo $output;
// =================================================================
?>
|
|