Q:

Factorial Program in Php

belongs to collection: PHP Programs

0

The factorial of a number n is defined by the product of all the digits from 1 to n (including 1 and n).

For example,

 

4! = 4*3*2*1 = 24  

6! = 6*5*4*3*2*1 = 720  

Note:

  • It is denoted by n! and is calculated only for positive integers.
  • Factorial of 0 is always 1.

The simplest way to find the factorial of a number is by using a loop.

There are two ways to find factorial in PHP:

  • Using loop
  • Using recursive method

Logic:

  • Take a number.
  • Take the descending positive integers.
  • Multiply them.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Factorial in PHP

Factorial of 4 using for loop is shown below.

Example:

<?php  
$num = 4;  
$factorial = 1;  
for ($x=$num; $x>=1; $x--)   
{  
  $factorial = $factorial * $x;  
}  
echo "Factorial of $num is $factorial";  
?>  

Output:

 

Factorial using Form in PHP

Below program shows a form through which you can calculate factorial of any number.

Example:

<html>  
<head>  
<title>Factorial Program using loop in PHP</title>  
</head>  
<body>  
<form method="post">  
    Enter the Number:<br>  
    <input type="number" name="number" id="number">  
    <input type="submit" name="submit" value="Submit" />  
</form>  
<?php   
    if($_POST){  
        $fact = 1;  
        //getting value from input text box 'number'  
        $number = $_POST['number'];  
        echo "Factorial of $number:<br><br>";  
        //start loop  
        for ($i = 1; $i <= $number; $i++){         
            $fact = $fact * $i;  
            }  
            echo $fact . "<br>";  
    }  
?>  
</body>  
</html>  

Output:

 

Factorial using Recursion in PHP

Factorial of 6 using recursion method is shown.

Example:

<?php  
function fact ($n)  
{  
    if($n <= 1)   
    {  
        return 1;  
    }  
    else   
    {  
        return $n * fact($n - 1);  
    }  
}  
  
echo "Factorial of 6 is " .fact(6);  
?>  

Output:

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Armstrong Number in Php... >>
<< Table of Number in Php...