function factorial($n) { if ($n == 0) { return 1; } else { return $n * factorial($n - 1); } } // Taking input from the user $number = readline("Enter a number: "); // Checking if the input number is a positive integer if ($number < 0) { echo "Factorial is not defined for negative numbers."; } elseif ($number == 0) { echo "Factorial of 0 is 1."; } else { $result = factorial($number); echo "Factorial of " . $number . " is " . $result; }

In this PHP program, we define a recursive function factorial() that calculates the factorial of a number $n. The function checks if the input number is 0. If it is, it returns 1 (as the factorial of 0 is defined as 1). Otherwise, it recursively multiplies $n with the factorial of $n-1 until $n becomes 0, resulting in the factorial of the original number.

The program then prompts the user to enter a number using readline(), and checks if it is a positive integer. If it is a negative number, it echoes a message stating that the factorial is not defined. If the number is 0, it directly outputs the factorial as 1. Otherwise, it calls the factorial() function with the input number and echoes the result using the echo statement.

Leave a Reply

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