This is another School / College fun program which is mostly been used in School lab to teach the basics of PHP such as if condition, for loop, multiplication, etc.,
So what is factorial? (if you don’t know already)
Multiplying given integer with the sequence of descending positive integers.
For example, The value of 5! is 120.
which is, 5 x 4 x 3 x 2 x 1 = 120
So, In this tutorial you are going to see you how to write a PHP program to find the n! using for loops!
See the program here,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<html> <body> <title>Factorial Program in PHP</title> <!-- form post method --> <form action="" method="post"> <label>Enter Number to calculate Factorial</label> <input type="text" name="number" size="2" /> </form> </body> </html> <?php //check for post value if there then allow inside if($_POST){ $fact = 1; //get the value from input text box 'number' $number = $_POST['number']; echo "Factorial of $number:<br><br>"; //loop till the iterator $i equals to $number for ($i = 1; $i <= $number; $i++){ //formula to calculate factorial is to //multiply the iterator $i value with $fact value. $fact = $fact * $i; //print $fact to show the factorial pyramid //or put this line out of this 'for loop' to show only the total value print $fact . "<br>"; } } ?> |
Read the comments in the program to understand how it is working.
I have also given an Online demo of this above PHP factorial program, see it here:
Enjoy the day!
Superb
hello why are you using same variable in $fact
this my code
$facts=”1″;
for ($i = 1; $i <= $num; $i++){
$fact = $facts * $i;
}
echo $fact . "”;
when i change it it’s not work explain it
Anurag,
You are using $fact instead of $facts
Missing ‘s’ in variable.