Calculate Factorial in PHP

Calculate Factorial in PHP

<?php
$n=5; // For calculating factorial of 5
$fact=1; // Initialising value of fact to 1
for($i=1; $i<=$n; $i++)
{
$fact = $fact * $i; // This statement i will explain below
}
echo $fact;
?>

// Here  first time $i= 1 and $fact=1;   then $fact=1
// Second time $i=2 and $fact=1     then $fact=2
// Third time $i=3 and $fact=2   then $fact=6
// Fourth time $i=4 and $fact=6  then $fact=24
// Fifth time $i=5 and $fact=24  then $fact=120;
// Sixth time loop will not be executed
// And echo will print the value of fact
__________________________________
See the video for program execution and output

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.