Program to print Factorial of any number

During our college days, we used to run various programs, some of them we used to understand and some of them we used to mug up. Once again i have thought to recall those programs and try to explain as simple as possible so that I can brainstorm myself and any students who go through it can easily get the logic behind it.

First of all, let us understand what is factorial of a number,

The factorial of a non-negative integer n is denoted by n! is the product of all positive integers less than or equal to n. example
Factorial of 4! = 1 * 2 * 3 *4 = 24
Factorial of 5! = 1 * 2 *3 * 4 * 5 = 120
n! = n*(n-1)*(n-2)*(n-3)…3.2.1

<?php 
$num=4;
$fact=1;

for($i=1;$i<=$num; $i++){
$fact=$i*$fact;
}

echo "factorial of a number ".$num is $fact;

In the above code, i am trying to find the factorial of a number 4, whereas I have initialized $fact variable with 1 as shown above, as we start our product of a number with 1.
Factorial of 4! = 1 * 2 * 3 *4 = 24

we are going to start from 1 and continue multiplying the number we have, ie. 4 so we are going to make use of for loop.
Now let us consider our looping. here we initialize variable $i with 1 and compare if it is less or equal to the number, so the first condition is correct (1<=4), so we go inside loop and execute the statement.

$fact= 1* 1 ($fact value that has been initialized)
$fact=1

now variable $i is incremented with one as we have $i++ in our loop so the new value of $i is $i=1+1=2;
now we will check the condition (2<=4), even this condition is correct so we execute the statement
$fact= $i*$fact
$fact= 2*1;($fact=1 which is previous value of $fact that we obtained after executing the statement)
$fact=2

Again $i is incremented by 1 and has become 2+1 =3, and we check condition (3<=4) which is again correct, so our statement becomes
$fact= $i*$fact
$fact= 3*2;($fact=2 which is previous value of $fact that we obtained after executing the statement)
$fact=6

Again $i is incremented by 1 and has become 3+1 =4, and we check condition (4<=4) which is again correct, so our statment becomes
$fact= $i*$fact
$fact= 4*6;($fact=6 which is previous value of $fact that we obtained after executing the statement)
$fact=24

Again $i is incremented by 1 and has become 4+1 =5, and we check condition (5<=4) which is false, so we come out of the loop and print the final factorial value.

So the final factorial value of 4 is 24

Advertisements