In this program, you will find factorial of number by using loop.
i) for loop
ii) while loop
iii) do while loop
2) using recursive function
3) using HTML form
factorial of a number is the multiplication of all its below number.
for example: 5! = 5*4*3*2*1 = 120
In this program factorial of 5 using the for loop program is shown:
<?php
$n=5;
$fact=1;
for($i=1;$i<=$n;$i++){
$fact=$fact*$i;
}
echo "factorial of 5 is: $fact";
?>
factorial of 5 is: 120
In this program factorial of 6 using the while loop program is shown:
<?php
$n=6;
$fact=1;
$i=1;
while($i<=$n){
$fact=$fact*$i;
$i++;
}
echo "factorial of 6 is: $fact";
?>
factorial of 6 is: 720
In this program factorial of 4 using do while loop program is shown:
<?php
$n=4;
$fact=1;
$i=1;
do{
$fact=$fact*$i;
$i++;
}while($i<=$n);
echo "factorial of 4 is: $fact";
?>
factorial of 4 is: 24
In this program factorial of 5 using the recursive method program is shown:
<?php
function factorial($n)
{
if($n>1)
{
return $n*factorial($n-1);
}
else{
return 1;
}
}
echo "factorial of 5 is:".factorial(5);
?>
factorial of 5 is:120
<!DOCTYPE html>
<html lang="en">
<head>
<title>factorial program</title>
</head>
<body>
<form>
Enter the number <input type="number" name="factorial">
<input type="submit" value="submit" name="click"></br>
</form>
</body>
</html>
<?php
if(isset($_GET["click"]))
{
$n=$_GET['factorial'];
$fact=1;
$i=1;
while($i<=$n){
$fact=$fact*$i;
$i++;
}
echo "factorial of $n is: $fact";
}
?>