INTRODUCTION

Site Home
LAMP Home
PHP Console Home
Getting Started
PHP Reference
Download Tutorial

LESSONS

01 Hello World!
02 Text I/O
03 Arithmetic
04 IF Statement
04 (b) Data Types
05 FOR Loop
06 Functions
07 While Loop
08 Do Loop
09 PHP Reference
10 Array
11 Classes
12 Menu
13 File I/O
14 Factorial N

MORE PHP

PHP in web pages
PHP and MySQL

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;
// =================================================================

?>