Factorial program in PHP using recursive function

Here, we are going to learn how to calculate the factorial of a given number using recursion in PHP?
Submitted by Nidhi, on November 19, 2020 [Last updated : March 12, 2023]

Factorial using Recursion

In this program, we will calculate the factorial of the specified given number. The factorial of 5 is 120.
5! = 5*4*3*2*1=120

PHP code to calculate the factorial using recursion

The source code to calculate the factorial of a given number using recursion is given below. The given program is compiled and executed successfully.

<?php
//PHP program to calculate the factorial 
//of a given number using recursion.
function fact($num)
{
    if ($num == 1) return 1;

    return $num * fact($num - 1);
}

$result = fact(5);
echo "Factorial is: " . $result;
?>

Output

Factorial is: 120

Explanation

In the above program, we created a recursive function fact() to calculate the factorial of a given number, The fact() function returns the factorial of the number to the calling function, in our program, we calculated the factorial of 5 that is 120.

PHP Basic Programs »





All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.