Factorial program in PHP

Factorial program in PHP

Factorial program in PHP

Factorial program in PHP:- Hi Readers, In this tutorial, I am going to explain how you can make the factorial program using PHP.

As you know In mathematics, the factorial of all non-negative integer n, denoted by n! is the product of all positive integers less than or equal to n. But here we write a program; how to print factorial of any number in PHP.

The main logic behind to find the factorial of a given number is, first of all, take any variable, say “factorial” and initialize it with 1. Now using loop either While, Do…While or For store the product of all integers starting from the given number whose factorial we want to find then (number-1), (number-2), …, 1.

i.e., factorial = number* (number -1)* (number -2)* (number -3) *… * 1.

Finally, Print or echo the value of factorial.

 

Factorial Example

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

Factorial program using While Loop

<?php

$fac_num = 6;

$factorial = 1;

$x = $fac_num;

While ( $x >= 1)

{

$factorial = $factorial * $x;

$x–;

}

echo “Factorial of $num is $factorial”;

?>

Factorial program using For Loop

<?php

$fac_num = 6;
$factorial = 1;
for ($x=$fac_num; $x>=1; $x--) 
{
 $factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";

?>


Factorial program using Do-While Loop

<?php

$fac_num = 6;

$factorial = 1;

$x = $fac_num;

Do{

$factorial = $factorial * $x;

$x–;

} While ( $x >= 1);

echo “Factorial of $num is $factorial”;

?>

Output

	
Factorial  of 6 is 720

Leave a Comment