PHP Program to Print Factorial of a Number using for loop


May 2, 2022, Learn eTutorial
1295

What is Factorial of a Number?

Factorial of a number is meant by product of all integer numbers from 1 to a given number. The factorial of a positive integer number is denoted by n! (where n is the number). For example, the factorial of number 3 (which is denoted as 3!) is 3 * 2 * 1 is 6. In this program, we are using for loop to find the factorial of a number. The factorial of 0 is always 1.

How to find the factorial of a number in PHP?

To find the factorial of a number in PHP we are using the for loop. At first, we accept the integer number from the user and saves it to a variable. Then we should check the number is positive or negative. If the number is negative we should have an error message else continue. Now we can perform the for loop till the condition is met and the result is obtained.

ALGORITHM

Step 1: Read an integer number into the variable num using the PHP function readline.

Step 2: Assign the value 1 into the variable fact to store the factorial result.

Step 4: Check the value of num is a positive number using if statement. If it is positive perform the following steps otherwise print "Enter a positive number." using echo

Step 5: Perform the for loop and assign the value of variable fact to variable x and perform the sub-steps until the condition 'fact >= 0' becomes false and decrement the value of variable x in every iteration

            (i) 'fact *= x' 

Step 6: Print the value of the variable fact as the factorial of the entered number using echo

PHP Source Code

                                          <?php
$num = (int)readline("Enter the number: "); // read number from user and type casted into integer
$fact = 1;                                   
if ($num >= 0) {                             // checking the number is positive or negative
    for ($x = $num; $x >= 1; $x--) {
        $fact *= $x;                         // multplying the value of fact with x
    }
    echo "Factorial of $num is $fact";      
} else {
    echo "Enter a positive integer.";
}
?>
                                      

OUTPUT

Enter the number: 4
Factorial of 4 is 24