PHP Practical Slip 16 Q.B

Write a PHP script to calculate the factorial of a number using a function.

<?php

// Function to calculate factorial
function factorial($num) {
    if ($num < 0) {
        return "Factorial is not defined for negative numbers.";
    }
    
    if ($num == 0 || $num == 1) {
        return 1;
    }

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

    return $fact;
}

// Example usage
$number = 5;
$result = factorial($number);

echo "Factorial of " . $number . " is: " . $result;

?>
Spread the love

Leave a Comment

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

Scroll to Top